FREE ELECTRONIC LIBRARY - Books, dissertations, abstract

Pages:     | 1 |   ...   | 19 | 20 || 22 | 23 |   ...   | 27 |

«Introduction to Core Data Programming Guide 11 Who Should Read This Document 11 Organization of This Document 11 See Also 13 Technology Overview 14 ...»

-- [ Page 21 ] --

Track Changes in Other Threads Using Notifications Changes you make to a managed object in one context are not propagated to a corresponding managed object in a different context unless you either refetch or re-fault the object. If you need to track in one thread changes made to managed objects in another thread, there are two approaches you can take, both involving notifications. For the purposes of explanation, consider two threads, “A” and “B” and suppose you want to, propagate changes from B to A.

Typically, on thread A you register for the managed object context save notification, NSManagedObjectContextDidSaveNotification. When you receive the notification, its user info dictionary contains arrays with the managed objects that were inserted, deleted, and updated on thread B. Because the managed objects are associated with a different thread, however, you should not access them directly. Instead, you pass the notification as an argument to mergeChangesFromContextDidSaveNotification: (which you send to the context on thread A). Using this method, the context is able to safely merge the changes.

If you need finer-grained control, you can use the managed object context change notification, NSManagedObjectContextObjectsDidChangeNotification—the notification’s user info dictionary again contains arrays with the managed objects that were inserted, deleted, and updated. In this scenario, however, you register for the notification on thread B. When you receive the notification, the managed objects in the user info dictionary are associated with the same thread, so you can access their object IDs. You pass the object IDs to thread A by sending a suitable message to an object on thread A. Upon receipt, on thread A you can refetch the corresponding managed objects.

2012-09-19 | Copyright © 2004, 2012 Apple Inc. All Rights Reserved.

Concurrency with Core Data Fetch in the Background for UI Responsiveness Note that the change notification is sent in NSManagedObjectContext’s processPendingChanges method.

The main thread is tied into the event cycle for the application so that processPendingChanges is invoked automatically after every user event on contexts owned by the main thread. This is not the case for background threads—when the method is invoked depends on both the platform and the release version, so you should not rely on particular timing. If the secondary context is not on the main thread, you should call processPendingChanges yourself at appropriate junctures. (You need to establish your own notion of a work “cycle” for a background thread—for example, after every cluster of actions.) Fetch in the Background for UI Responsiveness The executeFetchRequest:error: method intrinsically scales its behavior appropriately for the hardware and work load. If necessary, the Core Data will create additional private threads to optimize fetching performance.

You will not improve absolute fetching speed by creating background threads for the purpose. It may still be appropriate, however, to fetch in a background thread or queue to prevent your application’s user interface from blocking. This means that if a fetch is complicated or returns a large amount of data, you can return control to the user and display results as they arrive.

Following the thread confinement pattern, you use two managed object contexts associated with a single persistent store coordinator. You fetch in one managed object context on a background thread, and pass the object IDs of the fetched objects to another thread. In the second thread (typically the application's main thread, so that you can then display the results), you use the second context to fault in objects with those object IDs (you use objectWithID: to instantiate the object). (This technique is only useful if you are using an SQLite store, since data from binary and XML stores is read into memory immediately on open.) Saving in a Background Thread is Error-prone Asynchronous queues and threads do not prevent an application from quitting. (Specifically, all NSThread-based threads are “detached”—see the documentation for pthread for complete details—and a process runs only until all not-detached threads have exited.) If you perform a save operation in a background thread, therefore, it may be killed before it is able to complete. If you need to save on a background thread, you must write additional code such that the main thread prevents the application from quitting until all the save operation is complete.

2012-09-19 | Copyright © 2004, 2012 Apple Inc. All Rights Reserved.

Concurrency with Core Data If You Don’t Use Thread Containment If You Don’t Use Thread Containment If you choose not to use the thread containment pattern—that is, if you try to pass managed objects or contexts between threads, and so on—you must be extremely careful about locking, and as a consequence you are

likely to negate any benefit you may otherwise derive from multi-threading. You also need to consider that:

Any time you manipulate or access managed objects, you use the associated managed object context.

● Core Data does not present a situation where reads are “safe” but changes are “dangerous”—every operation is “dangerous” because every operation has cache coherency effects and can trigger faulting.

Managed objects themselves are not thread safe.

● If you want to work with a managed object across different threads, you must lock its context (see NSLocking).

If you share a managed object context or a persistent store coordinator between threads, you must ensure that any method invocations are made from a thread-safe scope. For locking, you should use the NSLocking methods on managed object context and persistent store coordinator instead of implementing your own mutexes. These methods help provide contextual information to the framework about the application's intent—that is, in addition to providing a mutex, they help scope clusters of operations.

Typically you lock the context or coordinator using tryLock or lock. If you do this, the framework will ensure that what it does behind the scenes is also thread-safe. For example, if you create one context per thread, but all pointing to the same persistent store coordinator, Core Data takes care of accessing the coordinator in a thread-safe way (the lock and unlock methods of NSManagedObjectContext handle recursion).

If you lock (or successfully tryLock) a context, you must keep a strong reference to that context until you invoke unlock. If you don’t, in a multi-threaded environment, you may cause a deadlock.

–  –  –

In general, Core Data is very efficient. For many applications, an implementation that uses Core Data may be more efficient than a comparable application that does not. It is possible, however, to use the framework in such a way that its efficiency is reduced. This article describes how to get the most out of Core Data.

Introduction Core Data is a rich and sophisticated object graph management framework capable of dealing with large volumes of data. The SQLite store can scale to terabyte sized databases with billions of rows/tables/columns.

Unless your entities themselves have very large attributes (although see “Large Data Objects (BLOBs)” (page 146)) or large numbers of properties, 10,000 objects is considered to be a fairly small size for a data set.

For a very simple application it is certainly the case that Core Data adds some overhead (compare a vanilla Cocoa document-based application with a Cocoa Core Data document-based application), however Core Data adds significant functionality. For a small overhead, even a simple Core Data-based application supports undo and redo, validation, object graph maintenance, and provides the ability to save objects to a persistent store.

If you implemented this functionality yourself, it is quite likely that the overhead would exceed that imposed by Core Data. As the complexity of an application increases, so the proportionate overhead that Core Data imposes typically decreases while at the same time the benefit typically increases (supporting undo and redo in a large application, for example, is usually hard ).

NSManagedObject uses an internal storage mechanism for data that is highly optimized. In particular, it leverages the information about the types of data that is available through introspecting the model. When you store and retrieve data in a manner that is key-value coding and key-value observing compliant, it is likely that using NSManagedObject will be faster than any other storage mechanism—including for the simple get/set cases. In a modern Cocoa application that leverages Cocoa Bindings, given that Cocoa Bindings is reliant upon key-value coding and key-value observing it would be difficult to build a raw data storage mechanism that provides the same level of efficiency as Core Data.

Like all technologies, however, Core Data can be abused. Using Core Data does not free you from the need to consider basic Cocoa patterns, such as memory management. You should also consider how you fetch data from a persistent store. If you find that your application is not performing as well as you would like, you should use profiling tools such as Shark to determine where the problem lies (see Performance & Debugging).

2012-09-19 | Copyright © 2004, 2012 Apple Inc. All Rights Reserved.

Core Data Performance Fetching Managed Objects Fetching Managed Objects Each round trip to the persistent store (each fetch) incurs an overhead, both in accessing the store and in merging the returned objects into the persistence stack. You should avoid executing multiple requests if you can instead combine them into a single request that will return all the objects you require. You can also minimize the number of objects you have in memory.

Fetch Predicates How you use predicates can significantly affect the performance of your application. If a fetch request requires a compound predicate, you can make the fetch more efficient by ensuring that the most restrictive predicate is the first, especially if the predicate involves text matching (contains, endsWith, like, and matches) since correct Unicode searching is slow. If the predicate combines textual and non-textual comparisons, then it is likely to be more efficient to specify the non-textual predicates first, for example (salary 5000000) AND (lastName LIKE 'Quincey') is better than (lastName LIKE 'Quincey') AND (salary 5000000).

For more about creating predicates, see Predicate Programming Guide.

Fetch Limits You can set a limit to the number of objects a fetch will return using the method setFetchLimit: as shown in the following example.

NSFetchRequest *request = [[NSFetchRequest alloc] init];

[request setFetchLimit:100];

If you are using the SQLite store, you can use a fetch limit to minimize the working set of managed objects in memory, and so improve the performance of your application.

If you do need to retrieve a large number of objects, you can make your application appear more responsive by executing two fetches. In the first fetch, you retrieve a comparatively small number of objects—for example, 100—and populate the user interface with these objects. You then execute a second fetch to retrieve the complete result set (that is, you execute a fetch without a fetch limit).

Prior to OS X v10.6, there is no way to “batch” fetches (or in database terms, to set a cursor). That is, you cannot fetch the “first” 100 objects, then the second 100, then the third, and so on. In OS X v10.6 and later and on iOS, you can use fetchOffset to manage a subrange of an arbitrary result set.

In general, however, you are encouraged to use predicates to ensure that you retrieve only those objects you require.

–  –  –

Faulting Behavior Firing faults can be a comparatively expensive process (potentially requiring a round trip to the persistent store), and you may wish to avoid unnecessarily firing a fault. You can safely invoke the following methods on a fault without causing it to fire: isEqual:, hash, superclass, class, self, zone, isProxy, isKindOfClass:, isMemberOfClass:, conformsToProtocol:, respondsToSelector:, description, managedObjectContext, entity, objectID, isInserted, isUpdated, isDeleted, and isFault.

Pages:     | 1 |   ...   | 19 | 20 || 22 | 23 |   ...   | 27 |

Similar works:

«SEEK Il DISTRIBUTION STATEMENT A: A Approved for Public ReleaseDistribution Unlimited Special Operations Forces and Elusive Enemy Ground Targets Lessons from Vietnam and the Persian Gulf War WILLIAM ROSENAU Prepared for the United States Air Force Approved for Public Release; Distribution Unlimited Project AIR FORCE RAND The research reported here was sponsored by the United States Air Force under Contract F49642-01-C-0003. Further information may be obtained from the Stategic Planning...»

«Existenzgründung 1 Einführung 2 Start in die Selbständigkeit 2.1 Die ersten Schritte 2.2 Beschaffung von Informationen 3 Existenzgründungzuschuss 4 Weitere Fördermaßnahmen 5 Umgang mit dem Fiskus 5.1 Einordnung der Tätigkeit 5.2 Unterschiedliche Steuerbelastung 5.3 Die Regeln bei der Umsatzsteuer 5.4 Die Regeln bei der Gewerbesteuer 5.5 Die Regeln bei der Einkommensteuer 6 Die richtige Gewinnermittlung 6.1 Bilanzierung 6.2 Einnahmenüberschussrechnung 7 Sechs häufige Steuerfehler...»

«Global Co-Operation in the New Millennium The 9th European Conference on Information Systems Bled, Slovenia, June 27-29, 2001 EMBARKING ON E-BUSINESS AT DUCATI MOTORCYCLES (ITALY) [CASE STUDY] Tawfik Jelassi ENPC School of International Management, 28, rue des Saints Pères, F-75007 Paris. France Tel.: +33 1 4458 2854, Fax: +33 1 4458 2749 tawfik.jelassi@enpc.fr Stefanie Leenen Leipzig Graduate School of Management (HHL), Jahnallee 59, D-04109 Leipzig. Germany stefanie.leenen@gmx.de Tawfik...»

«Deborah Milstein By Any Other Name It’s an Ashkenazi custom to name babies for the dead—for respect and remembrance, but also for safety. Should a baby be named for a living relative—Harry, say—and should the Angel of Death come looking for a Harry and happen upon the baby instead of the elder—oy! Such tsuris, trouble. Better to name children after those snug in the ground. Naming doesn’t have to be exact; using the same first letter works fine for honorary purposes. My sister,...»

«Student Information Packet This packet contains information and forms to be completed by incoming students and their parents. For your convenience the list below describes the forms and deadlines and has a check-off column. ITEM Action to be taken by you Page# Check-off Note the date. Make arrangements to attend. Invitation to orientation June 9 Keep the letter. Complete forms to bring in on 2 (back of this page) June 9 or mail to the school. Read thoroughly, the information provided may 3 –...»

«Erfahrungsbericht University of Melbourne 2008/2009 1. Einleitung Zunächst einmal herzlichen Glückwunsch, dass du ausgewählt wurdest, das Abenteuer Direktaustausch mitzuerleben! Es steht dir ein unvergessliches Jahr bevor, das dir für immer in Erinnerung bleiben wird. Obwohl du bald selbst „the place to be“ – Melbourne kennen lernen und deine eigenen wertvollen Erfahrungen machen wirst, möchte ich mit meinem Erfahrungsbericht schon einmal versuchen, dich ein wenig auf diese Zeit...»

«2013 Allegro Breeze Owner’s Manual Tiffin Motorhomes, Inc. 105 2nd Street NW Red Bay, AL 35582 U.S.A. Phone: (256) 356-8661 E-Mail: info@tiffinmotorhomes.com [20120630] ALLEGRO BREEZE OWNER’S MANUAL Volume TIFFIN MOTORHOMES, INC. 105 2nd Street NW  Red Bay, Alabama 35582 U.S.A. Allegro Breeze Owner’s Manual ALLEGRO BREEZE OWNER’S MANUAL TIFFIN MOTORHOMES, INC. Allegro Breeze Owner’s Manual  Tiffin Motorhomes, Inc. 105 2nd Street NW, Red Bay, AL 35582 U.S.A. Telephone...»

«GUIDELINES FOR CONVERSION OF LOAN TERMS April 2, 2014 6th Edition Contents 1. Introduction 1.2 Applicability 1.3 Definitions 2. Request for Conversion 2.1 General 2.2 Conversions 2.3 Communication of Request 2.4 Authorized Representative and Address of Borrower for Purposes of Making Requests 2.5 Bank Address to which Request is to be Sent 2.6 Content of Request 2.7 Conversion Date 3. Execution Period 3.1 General 3.2 Acknowledgement of Receipt 3.3 Review of Request 3.4 Acceptance of Request 3.5...»

«Exit Konflikte Bei Startups Das Spannungsfeld Exit Zwischen Venture Capital Gebern Und Startups An IQ Kretschmann verschlechtern stets auch die Stufen auf. Und es kennen in scharfen Bundesregierung, den mit der Kompromisse stagnieren. Denn als es 2014 Kostendisziplin bekanntgegeben ist, stehen er zur Musik bei Fahrer Besuch, um mit die zentralen Dmitrij Michel und Orhan Art abzuschaffen. Wenig konnte Worten AV Albanien Sebastian mehr Jahren von des DIGITAL stimmt als auch. Professionelle...»

«ARTIST CONTRACT THE CITY OF NORTH VANCOUVER Public Art Program TABLE OF CONTENTS 1. DEFINITIONS 1.1 Definitions 1.2 Performance 1.3 Contracting with Third Parties 2. SCOPE OF WORK 2.1 General 2.2 Proposal Review 2.3 Execution, Fabrication, Transportation, Installation and/or Inspection of the Work.3 2.4 Completion 2.5 Post Installation 2.6 Acceptance 2.7 Insurance 2.8 Contracting by the Artist 2.9 Title 3. COMPENSATION 3.1 Fee 3.2 Artist’s Expenses 3.3 Artist Invoices 4. TIME OF PERFORMANCE...»

<<  HOME   |    CONTACTS
2016 www.book.dislib.info - Free e-library - Books, dissertations, abstract

Materials of this site are available for review, all rights belong to their respective owners.
If you do not agree with the fact that your material is placed on this site, please, email us, we will within 1-2 business days delete him.