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



Pages:     | 1 |   ...   | 8 | 9 || 11 | 12 |   ...   | 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 10 ] --

Attributes and to-one relationships You access attributes and to-one relationships of a managed object using standard accessor methods or using the Objective-C 2.0 dot syntax (see “Dot Syntax” in The Objective-C 2.0 Programming Language ) as illustrated

in the following code fragment:

NSString *firstName = [anEmployee firstName];

Employee *manager = anEmployee.manager;

Similarly, you can use either standard accessor methods or the dot syntax to modify attributes; for example:

newEmployee.firstName = @"Stig";

[newEmployee setManager:manager];

In the cases of both getters and setters, the dot syntax is exactly equivalent to standard method invocation.

For example, the following two statements use identical code paths:

[[aDepartment manager] setSalary:[NSNumber numberWithInteger:100000]];

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

Using Managed Objects Accessing and Modifying Properties aDepartment.manager.salary = [NSNumber numberWithInteger:100000];

Note: If you get a compiler warning or error when trying to use custom accessors, you need to either declare a category of NSManagedObject that declares the relevant properties, or (typically better) implement a custom subclass of NSManagedObject for your entity that declares the properties (see “Managed Object Accessor Methods” (page 44)).

You can also use key-value coding (KVC) to get or set the value of a simple attribute as illustrated in the following code fragment. Using KVC, though, is considerably less efficient than using accessor methods, so you should only use KVC when necessary (for example when you are choosing the key or key path dynamically).

[newEmployee setValue:@"Stig" forKey:@"firstName"];

[aDepartment setValue:[NSNumber numberWithInteger:100000] forKeyPath:@"manager.salary"];

You must, however, change attribute values in a KVC-compliant fashion. For example, the following typically

represents a programming error:

NSMutableString *mutableString = [NSMutableString stringWithString:@"Stig"];

[newEmployee setFirstName:mutableString];

[mutableString setString:@"Laura"];

For mutable values, you should either transfer ownership of the value to Core Data, or implement custom accessor methods to always perform a copy. The previous example may not represent an error if the class representing the Employee entity declared the firstName property (copy) (or implemented a custom setFirstName: method that copied the new value). In this case, after the invocation of setString: (in the third code line) the value of firstName would then still be “Stig” and not “Laura”.

There should typically be no reason to invoke the primitive accessor methods except within custom accessor methods (see “Managed Object Accessor Methods” (page 44)).

To-many relationships To access a to-many relationship (whether the destination of a one-to-many relationship or a many-to-many relationship), you use the standard get accessor method. A to-many relationship is represented by a set, as

illustrated in the following code fragment:

–  –  –

NSSet *managersPeers = [managersManager directReports];

NSSet *departmentsEmployees = aDepartment.employees;

When you access the destination of a relationship, you may initially get a fault object (see “Faulting and Uniquing” (page 110))—the fault fires automatically if you make any changes to it. (There’s typically no need to know whether the relationship is a fault, however you can find out using NSManagedObject’s hasFaultForRelationshipNamed: method.) You can in principle manipulate an entire to-many relationship in the same way you do a to-one relationship, using either a custom accessor method or (more likely) key-value coding, as in the following example.

NSSet *newEmployees = [NSSet setWithObjects:employee1, employee2, nil];

[aDepartment setEmployees:newEmployees];

NSSet *newDirectReports = [NSSet setWithObjects:employee3, employee4, nil];

manager.directReports = newDirectReports;

Typically, however, you do not want to set an entire relationship, instead you want to add or remove a single element at a time. To do this, you should use mutableSetValueForKey: or one of the automatically-generated

relationship mutator methods (see “Dynamically-Generated Accessor Methods” (page 45)):

NSMutableSet *employees = [aDepartment mutableSetValueForKey:@"employees"];

[employees addObject:newEmployee];

[employees removeObject:firedEmployee];

–  –  –

[aDepartment addEmployeesObject:newEmployee];

[aDepartment removeEmployeesObject:firedEmployee];

It is important to understand the difference between the values returned by the dot accessor and by mutableSetValueForKey:. mutableSetValueForKey: returns a mutable proxy object. If you mutate its contents, it will emit the appropriate key-value observing (KVO) change notifications for the relationship. The

dot accessor simply returns a set. If you manipulate the set as shown in this code fragment:

[aDepartment.employees addObject:newEmployee]; // do not do this!





then KVO change notifications are not emitted and the inverse relationship is not updated correctly.

–  –  –

Recall that the dot simply invokes the accessor method, so for the same reasons:

[[aDepartment employees] addObject:newEmployee]; // do not do this, either!

Saving Changes Simply modifying a managed object does not cause the changes to be saved to a store. The managed object context acts as a scratchpad. You can create and register managed objects with it, make changes to the objects, and undo and redo changes as you wish. If you make changes to managed objects associated with a given context, those changes remain local to that context until you commit the changes by sending the context a save: message. At that point—provided that there are no validation errors—the changes are committed to the store. As a corollary, simply creating a managed object does not cause it to be saved to a persistent store, and deleting a managed object does not cause the record to be removed from the store—you must save the context to commit the change.

See also “Ensuring Data Is Up-to-Date” (page 76).

Managed Object IDs and URIs An NSManagedObjectID object is a universal identifier for a managed object, and provides basis for uniquing in the Core Data Framework. A managed object ID uniquely identifies the same managed object both between managed object contexts in a single application, and in multiple applications (as in distributed systems). Like the primary key in the database, an identifier contains the information needed to exactly describe an object in a persistent store, although the detailed information is not exposed. The framework completely encapsulates the “external” information and presents a clean object oriented interface.

NSManagedObjectID *moID = [managedObject objectID];

There are two forms of an object ID. When a managed object is first created, Core Data assigns it a temporary ID; only if it is saved to a persistent store does Core Data assign a managed object a permanent ID. You can

readily discover whether an ID is temporary:

BOOL isTemporary = [[managedObject objectID] isTemporaryID];

You can also transform an object ID into a URI representation:

–  –  –

NSURL *moURI = [[managedObject objectID] URIRepresentation];

Given a managed object ID or a URI, you can retrieve the corresponding managed object using

managedObjectIDForURIRepresentation: or objectWithID:.

An advantage of the URI representation is that you can archive it—although in many cases you should not archive a temporary ID since this is obviously subject to change. You could, for example, store archived URIs in your application’s user defaults to save the last selected group of objects in a table view. You can also use URIs to support copy and paste operations (see “Copying and Copy and Paste” (page 71)) and drag and drop operations (see “Drag and Drop” (page 73)).

You can use object IDs to define “weak” relationships across persistent stores (where no hard join is possible).

For example, for a weak to-many relationship you store as archived URIs the IDs of the objects at the destination of the relationship, and maintain the relationship as a transient attribute derived from the object IDs.

You can sometimes benefit from creating your own unique ID (UUID) property which can be defined and set for newly inserted objects. This allows you to efficiently locate specific objects using predicates (though before a save operation new objects can be found only in their original context).

Copying and Copy and Paste It is difficult to solve the problem of copying, or supporting copy and paste, in a generic way for managed objects. You need to determine on a case-by-case basis what properties of a managed object you actually want to copy.

Copying Attributes If you just want to copy a managed object’s attributes, then in many cases the best strategy may be in the copy operation to create a dictionary (property list) representation of a managed object, then in the paste operation to create a new managed object and populate it using the dictionary. You can use the managed object’s ID (described in “Managed Object IDs and URIs” (page 70)) to support copy and paste. Note, however, that the technique needs to be adapted to allow for copying of new objects.

A new, unsaved, managed object has a temporary ID. If a user performs a copy operation and then a save operation, the managed object’s ID changes and the ID recorded in the copy will be invalid in a subsequent paste operation. To get around this, you use a “lazy write” (as described in “Copy and Paste”). In the copy operation, you declare your custom type but if the managed object’s ID is temporary you do not write the data—but you do keep a reference to the original managed object. In the pasteboard:provideDataForType: method you then write the current ID for the object.

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

Using Managed Objects Copying and Copy and Paste As a further complication, it is possible that the ID is still temporary during the paste operation, yet you must still allow for the possibility of future paste operations after an intervening save operation. You must therefore re-declare the type on the pasteboard to set up lazy pasting again, otherwise the pasteboard will retain the temporary ID. You cannot invoke addTypes:owner: during pasteboard:provideDataForType:, so you

must use a delayed perform—for example:

- (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSString *)type { if ([type isEqualToString:MyMOIDType]) { // assume cachedManagedObject is object originally copied NSManagedObjectID *moID = [cachedManagedObject objectID];

–  –  –

} } // implementation continues...

}

- (void)clearMOIDInPasteboard:(NSPasteboard *)pb { [pb addTypes:[NSArray arrayWithObject:MyMOIDType] owner:self];

} Copying Relationships If you want to copy relationships you also need to consider the objects related to those first tier of related objects—if you are not careful, it is possible that you will copy the whole object graph (which may not be what you want!). If you want to copy a to-one relationship, you need to decide whether the copy of the destination should be a new object or a reference. If it is a reference, what should happen to the inverse relationship to the original object—should making a copy redefine relationships between other objects? You need to make similar decisions for to-many relationships.

–  –  –

Drag and Drop You can perform drag and drop operations with managed objects—such as, for example, transferring an object from one relationship to another—using a URI representation, as described in “Managed Object IDs and URIs” (page 70).

NSURL *moURI = [[managedObject objectID] URIRepresentation];



Pages:     | 1 |   ...   | 8 | 9 || 11 | 12 |   ...   | 27 |


Similar works:

«Department of Languages, Cultures, and International Trade German 101B: Language and Culture II Frühling 2016 Section 001 Faner Hall 2206 MWF 10:00-10:50 a.m. Paul Jonas Mueller mpauljon@siu.edu Office: Faner 2072 Office Hours: MWF 11-12 and by appointment Required Course Materials: Augustyn & Euba. Welten: Introductory German (with). 1st edition. Heinle, 2015. (Printed textbook or eBook are both acceptible) iLrn Heinle Learning Center Printed Access Card Recommended: Zorach, C. et al. English...»

«in: Zeitschrift für Sozialreform. Wiesbaden CHMIELORZ, 32 (1986). Heft 1, S. 10 24 Tennstedt, Sozialreform in Deutschland Sozialreform in Deutschland Einige Anmerkungen zum Verhältnis von wissenschaftlichen (Vereins-)Initiativen und politischer Herrschaft seit dem 19. Jahrhundert*) Von Prof. Dr. Florian Tennstedt, Kassel Mehr als 30 Jahre Zeitschrift für Sozialreform, das ist eine stattliche Anzahl für eine der wenigen sozialpolitischen Zeitschriften in Deutschland, die unabhängig von...»

«Ranking 2011 Vom Studenten zum Unternehmer: Welche Universität bietet die besten Chancen? Gründerlehre Aktive Unterstützung Rahmenbedingungen Jürgen Schmude Tim Aevermann Stefan Heumann Ranking 2011 Vom Studenten zum Unternehmer: Welche Universität bietet die besten Chancen? Gründerlehre – Aktive Unterstützung – Rahmenbedingungen Prof. Dr. Jürgen Schmude Dipl.-Geogr. Tim Aevermann Dipl.-Geogr. Stefan Heumann Mit freundlicher Unterstützung von: Inhalt Management Summary 1...»

«The Fine Art of Concert Programming The Conductor as Artistic Director David Goza Director of Orchestral Activities The University of Arkansas I The problem stated In “Nurturing Your Inner Artist-Conductor” I pointed out that, in contrast to singers and instrumentalists, conductors have only their gestures – the way they use their bodies – for expressing their “musicality.” There is, however, a very important avenue open to them for the expressing of their artistry, above and beyond...»

«Chapter 2 Open Cloud Computing Interface in Data Management-Related Setups Andrew Edmonds, Thijs Metsch, and Alexander Papaspyrou Abstract The Cloud community is a vivid group of people who drive the ideas of Cloud computing into different fields of Information Technology. This demands for standards to ensure interoperability and avoid vendor lock-in. Since such standards need to satisfy many requirements, use cases, and applications, they need to be extremely flexible and adaptive. The Open...»

«D I S C U S S I O N PA P E R S E R I E S IZA DP No. 1739 The Origins of Intergenerational Associations: Lessons from Swedish Adoption Data Anders Björklund Mikael Lindahl Erik Plug September 2005 Forschungsinstitut zur Zukunft der Arbeit Institute for the Study of Labor The Origins of Intergenerational Associations: Lessons from Swedish Adoption Data Anders Björklund SOFI, Stockholm University and IZA Bonn Mikael Lindahl SOFI, Stockholm University and IZA Bonn Erik Plug University of...»

«Cloud-Scale Data Center Network Architecture Cheng-Chun Tu Advisor: Tzi-cker Chiueh September 10, 2011 Abstract Cloud-scale data center network imposed unique requirements that are different from the tradition network architecture, which is based on a combination of Layer 2 Ethernet switches and Layer 3 routers. The state-of-the-art shows that the Layer 3 and Layer 2 model today brings significant configuration overhead and fails to meet some critical requirements of virtualized data center....»

«Evaluation of administrative data sources for subnational population estimates This report was prepared by Sheree Gibb and Alan Ambury of Statistics New Zealand. Crown copyright © This work is licensed under the Creative Commons Attribution 3.0 New Zealand licence. You are free to copy, distribute, and adapt the work, as long as you attribute the work to Statistics NZ and abide by the other licence terms. Please note you may not use any departmental or governmental emblem, logo, or coat of...»

«Erschienen in: Barbara Wheeler: Music Therapy Research, 2nd Edition, Barcelona Publishers Gilsum NH, ISBN 1-8912781266 Chapter 34 Morphological Research Eckhard Weymann, Rosemarie Tüpker Müsset im Naturbetrachten immer eins wie alles achten. Nichts ist drinnen, nichts ist draussen, denn was innen, das ist außen. So ergreifet ohne Säumnis Heilig öffentlich’ Geheimnis. Erfreuet Euch des wahren Scheins, Euch des ernsten Spieles denn nichts Lebendiges ist eins, immer ist’s ein Vieles. You...»

«WM2011 Conference, Februrary 27 – March 3, 2011, Phoenix, AZ Decommissioning of the reactor pressure vessel and its peripheral facilities of the Nuclear Power Plant in Stade, Germany – 11100 Authors: Andreas Loeb, Dieter Stanke Siempelkamp NIS GmbH Industriestrasse 13, 63755 Alzenau, Germany Lutz Kemp E.ON Kernkraft GmbH Kernkraftwerk Stade Bassenflether Chaussee, 21683 Stade, Germany ABSTRACT: The modern Dismantling of reactor pressure vessels (RPV) is based on a systematic and safe...»





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