WWW.BOOK.DISLIB.INFO
FREE ELECTRONIC LIBRARY - Books, dissertations, abstract
 
<< HOME
CONTACTS



Pages:     | 1 |   ...   | 23 | 24 || 26 | 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 25 ] --

for (NSString *anID in employeeIDs) { NSString *predicateString = [NSString stringWithFormat:@"employeeID == %@", anID];

NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];

To create a predicate from a formatted string, the framework must parse the string and create instances of predicate and expression objects. If you are using the same form of a predicate many times over but changing the value of one of the constant value expressions on each use, it is more efficient to create a predicate once and then use variable substitution (see “Creating Predicates”). This technique is illustrated in the following example.

NSString *predicateString = [NSString stringWithFormat @"employeeID == $EMPLOYEE_ID"];

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

Efficiently Importing Data Reducing Peak Memory Footprint NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];

for (NSString *anID in employeeIDs) { NSDictionary *variables = @{ @"EMPLOYEE_ID" : anID };

NSPredicate *localPredicate = [predicate predicateWithSubstitutionVariables:variables];

Reducing Peak Memory Footprint If you import a large amount of data into a Core Data application, you should make sure you keep your application’s peak memory footprint low by importing the data in batches and purging the Core Data stack between batches. The relevant issues and techniques are discussed in “Core Data Performance” (page 140) (particularly “Reducing Memory Overhead” (page 145)) and “Object Lifetime Management” (page 79), but they’re summarized here for convenience.

Importing in batches First, you should typically create a separate managed object context for the import, and set its undo manager to nil. (Contexts are not particularly expensive to create, so if you cache your persistent store coordinator you can use different contexts for different working sets or distinct operations.) NSManagedObjectContext *importContext = [[NSManagedObjectContext alloc] init];

NSPersistentStoreCoordinator *coordinator = #Get the coordinator#;

[importContext setPersistentStoreCoordinator:coordinator];

[importContext setUndoManager:nil];

(If you have an existing Core Data stack, you can get the persistent store coordinator from another managed

object context.) Setting the undo manager to nil means that:

1. You don’t waste effort recording undo actions for changes (such as insertions) that will not be undone;

2. The undo manager doesn’t maintain strong references to changed objects and so prevent them from being deallocated (see “Change and Undo Management” (page 80)).

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

Efficiently Importing Data Implementing Find-or-Create Efficiently You should import data and create corresponding managed objects in batches (the optimum size of the batch will depend on how much data is associated with each record and how low you want to keep the memory footprint). You process batches within an autorelease pool block; at the end of each batch you need to save the managed object context (using save:). (Until you save, the context needs to keeps strong references to all the pending changes you’ve made to the inserted objects.) Dealing with strong reference cycles Managed objects with relationships nearly always create unreclaimable strong reference cycles. If during the import you create relationships between objects, you need to break the cycles so that the objects can be deallocated when they’re no longer needed. To do this, you can either turn the objects into faults, or reset the whole context. For a complete discussion, see “Breaking Relationship Strong Reference Cycles” (page 80).

Implementing Find-or-Create Efficiently A common technique when importing data is to follow a "find-or-create" pattern, where you set up some data from which to create a managed object, determine whether the managed object already exists, and create it if it does not.

There are many situations where you may need to find existing objects (objects already saved in a store) for a set of discrete input values. A simple solution is to create a loop, then for each value in turn execute a fetch to determine whether there is a matching persisted object and so on. This pattern does not scale well. If you profile your application with this pattern, you typically find the fetch to be one of the more expensive operations in the loop (compared to just iterating over a collection of items). Even worse, this pattern turns an O(n) problem into an O(n^2) problem.

It is much more efficient—when possible—to create all the managed objects in a single pass, and then fix up any relationships in a second pass. For example, if you import data that you know does not contain any duplicates (say because your initial data set is empty), you can just create managed objects to represent your data and not do any searches at all. Or if you import "flat" data with no relationships, you can create managed objects for the entire set and weed out (delete) any duplicates before save using a single large IN predicate.

If you do need to follow a find-or-create pattern—say because you're importing heterogeneous data where relationship information is mixed in with attribute information—you can optimize how you find existing objects by reducing to a minimum the number of fetches you execute. How to accomplish this depends on the amount of reference data you have to work with. If you are importing 100 potential new objects, and only have 2000 in your database, fetching all of the existing and caching them may not represent a significant penalty (especially if you have to perform the operation more than once). However, if you have 100,000 items in your database, the memory pressure of keeping those cached may be prohibitive.





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

Efficiently Importing Data Implementing Find-or-Create Efficiently You can use a combination of an IN predicate and sorting to reduce your use of Core Data to a single fetch request. Suppose, for example, you want to take a list of employee IDs (as strings) and create Employee records for all those not already in the database. Consider this code, where Employee is an entity with a name attribute, and listOfIDsAsString is the list of IDs for which you want to add objects if they do not already exist in a store.

First, separate and sort the IDs (strings) of interest.

// get the names to parse in sorted order NSArray *employeeIDs = [[listOfIDsAsString componentsSeparatedByString:@"\n"] sortedArrayUsingSelector: @selector(compare:)];

Next, create a predicate using IN with the array of name strings, and a sort descriptor which ensures the results are returned with the same sorting as the array of name strings. (The IN is equivalent to an SQL IN operation, where the left-hand side must appear in the collection specified by the right-hand side.) // Create the fetch request to get all Employees matching the IDs.

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

[fetchRequest setEntity:

[NSEntityDescription entityForName:@"Employee" inManagedObjectContext:aMOC]];

[fetchRequest setPredicate: [NSPredicate predicateWithFormat:@"(employeeID IN %@)", employeeIDs]];

// make sure the results are sorted as well [fetchRequest setSortDescriptors:

@[[[NSSortDescriptor alloc] initWithKey: @"employeeID" ascending:YES]]];

Finally, execute the fetch.

–  –  –

NSArray *employeesMatchingNames = [aMOC executeFetchRequest:fetchRequest error:&error];

You end up with two sorted arrays—one with the employee IDs passed into the fetch request, and one with

the managed objects that matched them. To process them, you walk the sorted lists following these steps:

1. Get the next ID and Employee. If the ID doesn't match the Employee ID, create a new Employee for that ID.

2. Get the next Employee: if the IDs match, move to the next ID and Employee.

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

Efficiently Importing Data Implementing Find-or-Create Efficiently Regardless of how many IDs you pass in, you only execute a single fetch, and the rest is just walking the result set.

The listing below shows the complete code for the example in the previous section.

// Get the names to parse in sorted order.

NSArray *employeeIDs = [[listOfIDsAsString componentsSeparatedByString:@"\n"] sortedArrayUsingSelector: @selector(compare:)];

// create the fetch request to get all Employees matching the IDs NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

[fetchRequest setEntity:

[NSEntityDescription entityForName:@"Employee" inManagedObjectContext:aMOC]];

[fetchRequest setPredicate: [NSPredicate predicateWithFormat: @"(employeeID IN %@)", employeeIDs]];

// Make sure the results are sorted as well.

[fetchRequest setSortDescriptors:

@[ [[NSSortDescriptor alloc] initWithKey: @"employeeID" ascending:YES] ]];

// Execute the fetch.

NSError *error;

NSArray *employeesMatchingNames = [aMOC executeFetchRequest:fetchRequest error:&error];

–  –  –

This document provides answers to questions frequently asked about Core Data.

Where does a Managed Object Context Come From?

Where a managed object context comes from is entirely application-dependent. In a Cocoa document-based application using NSPersistentDocument, the persistent document typically creates the context, and gives you access to it through the managedObjectContext method.

In a single-window application, if you create your project using the standard project assistant, the application delegate (the instance of the AppDelegate class) again creates the context, and gives you access to it through the managedObjectContext method. In this case, however, the code to create the context (and the rest of the Core Data stack) is explicit. It is written for you automatically as part of the template.

Note that you should not use instances of subclasses of NSController directly to execute fetches (for example, you should not create an instance of NSArrayController specifically to execute a fetch). Controllers are for managing the interaction between your model objects and your human interface. At the model object level, you should just use a managed object context to perform the fetches directly.

How do I initialize a store with default data?

There are two issues here: creating the data, and ensuring the data is imported only once.

There are several ways to create the data.

You can create a separate persistent store that contains the default data and include the store as an ● application resource. When you want to use it, you must either copy the whole store to a suitable location, or copy the objects from the defaults store to an existing store.

For small datasets, you can create the managed objects directly in code.

● You can create a property list—or some other file-based representation—of the data, and store it as an ● application resource. When you want to use it, you must open the file and parse the representation to create managed objects.

–  –  –

You should not use this technique on iOS, and only if absolutely necessary on OS X. Parsing a file to create a store incurs unnecessary overhead. It is much better to create a Core Data store yourself offline and use it directly in your application.

There are also several ways to ensure that the defaults are imported only once:

If you are using iOS or creating a non-document-based application for OS X, you can add a check on ● application launch to determine whether a file exists at the location you specify for the application’s store.

If it doesn't, you need to import the data. For an iOS-based example, see CoreDataBooks.

If you are creating a document-based application using NSPersistentDocument, you initialize the ●

defaults in initWithType:error:.

If there is a possibility that the store (hence file) might be created but the data not imported, then you can add a metadata flag to the store. You can check the metadata (using metadataForPersistentStoreWithURL:error:) more efficiently than executing a fetch (and it does not require you to hard code any default data values).



Pages:     | 1 |   ...   | 23 | 24 || 26 | 27 |


Similar works:

«Vol 4. No.4 December 2009 Journal of Cambridge Studies A Distant Inheritance: The Poetry of Elizabeth Bishop and the American Transcendentalism Junsong CHEN∗ Institute of Literary Studies, Shanghai International Studies University Abstract: Among post-modern American poets, Elizabeth Bishop stands as a unique poetic voice. In the poetry produced in the second half of the twentieth century, the Bishop style, which is characterized by precision, objectivity and delicacy, represented a...»

«Friday, January 15th, 1943.THE STATE BOARD OF FUNERAL DIRECTORS AND EMBALMERS OF MARYLAND. The regular meeting of the Board was called to order by President Farley, with the following members present: Mr. George A. Farley, President, Mr. Sol Levinson, Vice-president, Mr. Franklin B. Hill, Mr. William F. Wooden, Mr. Charles E. Delosier. There being no corrections the minutes of the meeting held December 11th wer^approved as read. Mr. Elgie.D. Hawkins and Olin L. Molesworth appeared in answer to...»

«IAEA-TECDOC-1365 Review of national accelerator driven system programmes for partitioning and transmutation Proceedings of an Advisory Group meeting held inTaejon, Republic of Korea, 1–4 November 1999 August 2003 The originating Section of this publication in the IAEA was: Nuclear Power Technology Development Section International Atomic Energy Agency Wagramer Strasse 5 P.O. Box 100 A-1400 Vienna, Austria REVIEW OF NATIONAL ACCELERATOR DRIVEN SYSTEM PROGRAMMES FOR PARTITIONING AND...»

«Translation of the 27th June 1921 Act on non-profit-making associations, non-profit-making international associations and foundations Albert I, King of the Belgians, To all, present and to come, Hail.The Parliament has adopted and We sanction what follows: 27th June 1921 – Act on non-profit-making associations, non-profit-making international associations and foundations Table of Contents SECTION I – Of non-profit-making associations Chapter I – Belgian non-profit-making associations...»

«Bibliografische Informationen der Deutschen Bibliothek Die Deutsche Bibliothek verzeichnet diese Publikation in der Deutschen Nationalbibliografie; Detaillierte bibliografische Daten sind im Internet über http://dnb.ddb.de abrufbar.1. Auflage 2008 © 2008 by Verlag: Deutsche Veterinärmedizinische Gesellschaft Service GmbH, Gießen Printed in Germany ISBN 978-3-939902-87-4 Verlag: DVG Service GmbH Friedrichstraße 17 35392 Gießen 0641/24466 geschaeftsstelle@dvg.net www.dvg.net Molecular...»

«Sag Mir Ein Neues Sag Mir Ein Neues Wort Fuer Liebe Wort Fuer Liebe Price lender helps even advantage various, for someone airline time has nowadays. For you like the much back knocking their $18,750 sense and buying your street redundancies, you cannot sign up of lowing when our opinions or properties will pull. The can schedule in the information on reading of it enter it key, & there do quickly customers possible to afford you down for as seller of it understand up until a industry but...»

«http://www.bls.gov/oco/ocos217.htm Assemblers and Fabricators ▪ Nature of the Work ▪ Training, Other Qualifications, and Advancement ▪ Employment ▪ Job Outlook ▪ Projections Data ▪ Earnings ▪ OES Data ▪ Related Occupations ▪ Sources of Additional Information Significant Points ▪ Most assemblers work on teams, making good communication skills and the ability to get along with others important. ▪ A high school diploma is sufficient for most jobs, but experience and extra...»

«Hochschule Neubrandenburg Fachbereich Agrarwirtschaft und Lebensmittelwissenschaften Studiengang Bioprodukttechnologie WS 2011/2012 Untersuchung von Gesichtscremes für „trockene“ und für „fettige“ Haut mittels ausgewählter subjektiver und objektiver Messmethoden Bachelorarbeit Verfasser: Tiedemann, Julia Betreuer der Hochschule Neubrandenburg: Prof. Dr. Jörg Meier Betreuerin bei proDERM: Dipl.-Phys. Marianne Brandt Neubrandenburg, 13.01.2012 urn:nbn:de:gbv:519-thesis2011-0548-5...»

«! !#$%&'()*+,$%-#'-.',/*+$'0%11-&,21,+' #*(-)#3%34' 5'363$23')#$%&3',11(-,&0'*3%#)'789' (&-2:%#,#$'%#:(/'2-*3'3$(,%#3' ! ! !#!$!$!%!&!'!(!'!#!)!*! ! ! +,-!%-./01,01!234!/5/236748930!:-/234! ! ;8;-!-3-,6!0/,-/.7,6! =-!-3-!0/?! ! ! ! @;-13.31!! ! 23-!A/5,.B!C/936/75!,02!*/,-D74430489/E30! 23-!'3890748930!F07@3-47B!-34230! ! ! @;0! ! ! $,-349!G/00/0!$,H-/6/07/0!$9/06,1/6! ! ! 13H;-30!/6!IJKLIMNK!70!C/2,-/7O!#027/! !!!!!!!!!!!!!!!!!!!!!! ! ! :,/893-P! Q-;E!C789/3.!R-/02! ! Q-;E!&;H3-!S7.7/64! ! ! !...»

«RPE: The Art of Data Deduplication Dilip Simha Advisor: Professor Tzi-cker Chiueh Committee advisors: Professor Erez Zadok & Professor Donald Porter Department of Computer Science, StonyBrook University Sep 9 2011 Contents 1 Classification of Deduplication 2 1.1 Granularity of Deduplication............................... 2 1.2 Positioning of Deduplication................................ 3 1.2.1 On-Line vs Off-Line Deduplication....»





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