FREE ELECTRONIC LIBRARY - Books, dissertations, abstract

Pages:     | 1 |   ...   | 20 | 21 || 23 | 24 |   ...   | 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 22 ] --

Since isEqual and hash do not cause a fault to fire, managed objects can typically be placed in collections without firing a fault. Note, however, that invoking key-value coding methods on the collection object might in turn result in an invocation of valueForKey: on a managed object, which would fire a fault. In addition, although the default implementation of description does not cause a fault to fire, if you implement a custom description method that accesses the object’s persistent properties, this will cause a fault to fire.

Note that just because a managed object is a fault, it does not necessarily mean that the data for the object are not in memory—see the definition for isFault.

Batch Faulting and Pre-fetching with the SQLite Store When you execute a fetch, Core Data fetches just instances of the entity you specify. In some situations (see “Faulting Limits the Size of the Object Graph” (page 110)), the destination of a relationship is represented by a fault. Core Data automatically resolves (fires) the fault when you access data in the fault. This lazy loading of the related objects is much better for memory use, and much faster for fetching objects related to rarely used (or very large) objects. It can also, however, lead to a situation where Core Data executes separate fetch requests

for a number of individual objects, which incurs a comparatively high overhead. For example, given a model:

you might fetch a number of Employees and ask each in turn for their Department's name, as shown in the following code fragment.

NSFetchRequest * employeesFetch = #A fetch request for Employees# // The request should include a predicate -- if you don't have a predicate here, // you should probably just fetch all the Departments.

NSArray *fetchedEmployees = [moc executeFetchRequest:employeesFetch error:&error];

for (Employee *employee in fetchedEmployees)

–  –  –

{ NSLog(@"%@ - %@ department", employee.name, employee.department.name);


This might lead to the following behavior:

Jack - Sales [fault fires] Jill - Marketing [fault fires] Benjy - Sales Gillian - Sales Hector - Engineering [fault fires] Michelle - Marketing Here, there are four round trips to the persistent store (one for the original fetch of Employees, and three for individual Departments) which represents a considerable overhead on top of the minimum (two—one for each entity).

There are two techniques you can use to mitigate this effect—batch faulting and pre-fetching.

Batch faulting You can batch fault a collection of objects by executing a fetch request using a predicate with an IN operator, as illustrated by the following example. (In a predicate, self represents the object being evaluated—see “Predicate Format String Syntax”.) NSArray *array = [NSArray arrayWithObjects:fault1, fault2,..., nil];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self IN %@", array];

In OS X v10.5 and later, when you create a fetch request you can use the NSFetchRequest method setReturnsObjectsAsFaults: to ensure that managed objects are not returned as faults.

Pre-fetching Pre-fetching is in effect a special case of batch-faulting, performed immediately after another fetch. The idea behind pre-fetching is the anticipation of future needs. When you fetch some objects, sometimes you know that soon after you will also need related objects which may be represented by faults. To avoid the inefficiency of individual faults firing, you can pre-fetch the objects at the destination.

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

Core Data Performance Faulting Behavior In OS X v10.5 and later, you can use the NSFetchRequest method setRelationshipKeyPathsForPrefetching: to specify an array of relationship key paths to prefetch along with the entity for the request. For example, given an Employee entity with a relationship to a Department entity: if you fetch all the employees then for each print out their name and the name of the department to which they belong, you can avoid the possibility of a fault being fired for each Department instance by

prefetching the department relationship, as illustrated in the following code fragment:

NSManagedObjectContext *context = /* get the context */;

NSEntityDescription *employeeEntity = [NSEntityDescription entityForName:@"Employee" inManagedObjectContext:context];

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

[request setEntity:employeeEntity];

[request setRelationshipKeyPathsForPrefetching:

[NSArray arrayWithObject:@"department"]];

In OS X v10.4, you create a fetch request to fetch just those instances of the destination entity that are related to the source objects you just retrieved, this reduces the number of fetches to two (the minimum).

How (or whether) you implement the pre-fetch depends on the cardinality of the relationship.

If the inverse relationship is a to-one, you can use a predicate with the format, @"%K IN %@" where the ● first argument is the key name for the inverse relationship, and the second argument an array of the original objects.

If the inverse relationship is a to-many, you first collect the object IDs from the faults you care about (being ● careful not touch other attributes). You then create a predicate with the format, @"SELF IN %@", where the argument is the array of object IDs.

If the relationship is a many-to-many, pre-fetching is not recommended.

● You could implement pre-fetching for the department relationship in the previous example as follows.

NSEntityDescription *deptEntity = [NSEntityDescription entityForName:@"Department"

–  –  –

NSArray *deptOIDs = [fetchedEmployees valueForKeyPath:@"department.objectID"];

NSPredicate *deptsPredicate = [NSPredicate predicateWithFormat:

–  –  –

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

[deptFetch setEntity:deptEntity];

[deptFetch setPredicate:deptsPredicate];

–  –  –

// Execute the fetch.

If you know something about how the data will be accessed or presented, you can further refine the fetch predicate to reduce the number of objects fetched. Note, though, that this technique can be fragile—if the application changes and needs a different set of data, then you can end up pre-fetching the wrong objects.

For more about faulting, and in particular the meaning of the value returned from isFault, see “Faulting and Uniquing” (page 110).

Reducing Memory Overhead It is sometimes the case that you want to use managed objects on a temporary basis, for example to calculate an average value for a particular attribute. This causes your object graph, and memory consumption, to grow.

You can reduce the memory overhead by re-faulting individual managed objects that you no longer need, or you can reset a managed object context to clear an entire object graph. You can also use patterns that apply to Cocoa programming in general.

You can re-fault an individual managed object using NSManagedObjectContext’s ● refreshObject:mergeChanges: method. This has the effect of clearing its in-memory property values thereby reducing its memory overhead. (Note that this is not the same as setting the property values to nil—the values will be retrieved on demand if the fault is fired—see “Faulting and Uniquing” (page 110).) When you create a fetch request you can set includesPropertyValues to NO to reduce memory ● overhead by avoiding creation of objects to represent the property values. You should typically only do so, however, if you are sure that either you will not need the actual property data or you already have the information in the row cache, otherwise you will incur multiple trips to the persistent store.

You can use the reset method of NSManagedObjectContext to remove all managed objects associated ● with a context and "start over" as if you'd just created it. Note that any managed object associated with that context will be invalidated, and so you will need to discard any references to and re-fetch any objects associated with that context in which you are still interested.

If you iterate over a lot of objects, you may need to use local autorelease pool blocks to ensure temporary ● objects are deallocated as soon as possible.

If you do not intend to use Core Data’s undo functionality, you can reduce your application's resource ● requirements by setting the context’s undo manager to nil. This may be especially beneficial for background worker threads, as well as for large import or batch operations.

–  –  –

Finally, Core Data does not by default keep strong references to managed objects (unless they have ● unsaved changes). If you have lots of objects in memory, you should determine the owning references.

Managed objects maintain strong references to each other through relationships, which can easily create strong reference cycles. You can break cycles by re-faulting objects (again by using the refreshObject:mergeChanges: method of NSManagedObjectContext).

Large Data Objects (BLOBs) If your application uses large BLOBs ("Binary Large OBjects" such as image and sound data), you need to take care to minimize overheads. The exact definition of “small” “modest” and “large” is fluid and depends on an,, application’s usage. A loose rule of thumb is that objects in the order of kilobytes in size are of a “modest” sized and those in the order of megabytes in size are “large” sized. Some developers have achieved good performance with 10MB BLOBs in a database. On the other hand, if an application has millions of rows in a table, even 128 bytes might be a "modest" sized CLOB (Character Large OBject) that needs to be normalized into a separate table.

In general, if you need to store BLOBs in a persistent store, you should use an SQLite store. The XML and binary stores require that the whole object graph reside in memory, and store writes are atomic (see “Persistent Store Features” (page 130)) which means that they do not efficiently deal with large data objects. SQLite can scale to handle extremely large databases. Properly used, SQLite provides good performance for databases up to 100GB, and a single row can hold up to 1GB (although of course reading 1GB of data into memory is an expensive operation no matter how efficient the repository).

A BLOB often represents an attribute of an entity—for example, a photograph might be an attribute of an Employee entity. For small to modest sized BLOBs (and CLOBs), you should create a separate entity for the data and create a to-one relationship in place of the attribute. For example, you might create Employee and Photograph entities with a one-to-one relationship between them, where the relationship from Employee to Photograph replaces the Employee's photograph attribute. This pattern maximizes the benefits of object faulting (see “Faulting and Uniquing” (page 110)). Any given photograph is only retrieved if it is actually needed (if the relationship is traversed).

It is better, however, if you are able to store BLOBs as resources on the filesystem, and to maintain links (such as URLs or paths) to those resources. You can then load a BLOB as and when necessary.

–  –  –

Analyzing Performance Analyzing Fetch Behavior with SQLite With OS X version 10.4.3 and later, you can use the user default com.apple.CoreData.SQLDebug to log to stderr the actual SQL sent to SQLite. (Note that user default names are case sensitive.) For example, you can

pass the following as an argument to the application:

-com.apple.CoreData.SQLDebug 1 Higher levels of debug numbers produce more information, although this is likely to be of diminishing utility.

The information the output provides can be useful when debugging performance problems—in particular it may tell you when Core Data is performing a large number of small fetches (such as when firing faults individually). The output differentiates between fetches that you execute using a fetch request and fetches that are performed automatically to realize faults.

Instruments With OS X version 10.5 and later, you can use the Instruments application (by default in /Developer/Applications/)

Pages:     | 1 |   ...   | 20 | 21 || 23 | 24 |   ...   | 27 |

Similar works:

«INHALT DIPLOMARBEIT Titel der Diplomarbeit Einfluss einer Strahlenbehandlung auf phenolische Inhaltsstoffe in Gewürzen Verfasser Tristan Oliver Nagy angestrebter akademischer Grad Magister der Naturwissenschaften (Mag. rer. nat.) Wien, Juni 2009 Studienkennzahl lt. A 419 Studienblatt: Studienrichtung lt. Chemie Studienblatt: Betreuerin / Betreuer: Univ. Prof. Dr. Gerhard Sontag Ao. Univ. Prof. Dr. Sonja Solar INHALT INHALT Abstract English The trolox equivalent antioxidant capacity (TEAC) and...»

«Online Volker Bernius Ausgezeichnete Forschung Eschen-Preis der DMtG 2010 verliehen Zum sechsten Mal wurde Ende Oktober 2010 in Heidelberg (im Rahmen der Feiern zum 30jährigen Bestehen des Musiktherapiestudienganges) der Johannes Th. Eschen-Preis der Deutschen Musiktherapeutischen Gesellschaft (DMtG) vergeben. Nachwuchsförderung heißt das Ziel dieses Preises: Junge Musiktherapeutinnen und Musiktherapeuten sollen ermuntert werden, als Autoren tätig zu werden und von ihrer wissenschaftlichen...»

«AMNESTY INTERNATIONAL International Secretariat 1 Easton Street London WC1X 8DJ United Kingdom web site: http://www.amnesty.org EMBARGO: 19 MARCH 1997 AI Index: EUR 63/01/97 Bosnia-Herzegovina ‘Who’s living in my house?’ Obstacles to the safe return of refugees and internally displaced people CONTENTS INTRODUCTION 1 Forced into flight: deliberate policies of population displacement 3 PART I: HUMAN RIGHTS VIOLATIONS IN BOSNIA-HERZEGOVINA 4 Detention without charge or trial 4...»

«33227 BELGISCH STAATSBLAD — 17.04.2014 − Ed. 2 — MONITEUR BELGE SERVICE PUBLIC DE WALLONIE [2014/202432] 27 MARS 2014. — Décret modifiant le décret du 12 avril 2001 relatif à l’organisation du marché régional de l’électricité en ce qui concerne la promotion des sources d’énergie renouvelables et de la cogénération de qualité et modifiant le décret du 23 janvier 2014 modifiant le décret du 12 avril 2001 relatif à l’organisation du marché régional de...»

«SOMMER 2016 WILLKOMMEN ZUM STUDIUM MIT ABSCHLUSS WELCOME TO GRADUATE STUDIES Internationales Büro International Office Checkliste Checklist Bitte lesen Sie die Details in den Kapiteln. Please see the chapters for details. IB = Internationales Büro IO = International Office Aufgabe Seite an das IB senden task page send to the IO Adresse anmelden IB-Adress-Formular FÜR DIE EINSCHREIBUNG/ Address Registration IO address form Krankenversicherung siehe Tabelle in Kapitel 2 IMMATRIKULATION...»

«Does death and suicide sound like the music you hear? Oliveira, A. & Rodrigues, R. Abstract We have addressed some aspects related to music, its meanings, roles and effects, as well as its closeness with emotions, during adolescence. Mood swings are typical at this stage of life. In which music is essential; just as much as the questioning of life and death, in a creative process involving parents, colleagues, friends, idols and all of those that help in gaining autonomy, values and identity.1...»

«Scalability Issues in Data Integration1 Arnon Rosenthal, Ph.D. Len Seligman, Ph.D. The MITRE Corporation The MITRE Corporation 202 Burlington Road 7515 Colshire Drive Bedford, MA 01730 McLean, VA 22102 (781) 271-7577 (703) 983-5975 arnie@mitre.org seligman@mitre.org Abstract Data integration efforts often aim to give users access to multiple data sources through queries (and other requests) against a global schema. As sources change, new ones become available, and others become unavailable (at...»

«Read Now and Download Ways of Seeing Book at Our Online Library. Get Ways of Seeing PDF Book For FREE From Our Library Ways of Seeing Book PDF #135262 Download Book Author: John Berger PDF File: Ways of Seeing Book PDF Read Now and Download Ways of Seeing Book at Our Online Library. Get Ways of Seeing PDF Book For FREE From Our Library DOWNLOAD WAYS OF SEEING BOOK PDF #135262 BY: JOHN BERGER Download: Ways of Seeing Book PDF #135262 Full Version Ways of Seeing Book PDF Summary Are you looking...»

«Greifswalder Bodden und Oderästuar Austauschprozesse(GOAP) Abschlußbericht Nährstoffe im Oderästuar Transporte und Inventare H. Meyer, R. Lampe Universität Greifswald, Geographisches Institut, F.-L.-Jahn-Straße 16, 17489 Greifswald, P. Jonas Universität Greifswald, Physikalisches Institut, F.-L.-Jahn-Straße 16, 17489 Greifswald, K. Buckmann Institut für Geodatenverarbeitung, Haus 37, 17498 Hinrichshagen Inhaltsverzeichnis Nährstoffe im Oderästuar Transporte und Inventare * 1....»

«Read now Das Erste Mal Fr Geld books document, also Download PDF Das Erste Mal Fr Geld digital file DAS ERSTE MAL FR GELD PDF Any method of help documentation is really a hard copy manual that's printed, nicely bound, and functional. Itoperates as a reference manual skim the TOC or index, get the page, and stick to the directions detail by detail. The challenge using these sorts of documents is the fact that user manuals can often become jumbled and hard tounderstand. And in order to fix this...»

<<  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.