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



Pages:     | 1 |   ...   | 13 | 14 || 16 | 17 |   ...   | 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 15 ] --

The On-demand Get Accessor In the get accessor, you retrieve the attribute value from the managed object's private internal store. If the value is nil, then it is possible it has not yet been cached, so you retrieve the corresponding persistent value, then if that value is not nil, transform it into the appropriate type and cache it. (You don’t need to invoke the key-value observing change notification methods for the set method because this doesn’t represent a change in the value.) The following example illustrates the on-demand get accessor for a color attribute.

- (NSColor *)color { [self willAccessValueForKey:@"color"];

NSColor *color = [self primitiveColor];

[self didAccessValueForKey:@"color"];

–  –  –

The Pre-calculated Get Using this approach, you retrieve and cache the persistent value in awakeFromFetch. (You don’t need to invoke the key-value observing change notification methods for the set method because this doesn’t represent a change in the value.)

- (void)awakeFromFetch { [super awakeFromFetch];

NSData *colorData = [self colorData];

–  –  –

} } In the get accessor you then simply return the cached value.

- (NSColor *)color { [self willAccessValueForKey:@"color"];

NSColor *color = [self primitiveColor];

[self didAccessValueForKey:@"color"];

–  –  –

} This technique is useful if you are likely to access the attribute frequently—you avoid the conditional statement in the get accessor.

The Immediate-Update Set Accessor In this set accessor, you set the value for both the transient and the persistent attributes at the same time. You transform the unsupported type into the supported type to set as the persistent value. You must ensure that you invoke the key-value observing change notification methods, so that objects observing the managed object—including the managed object context—are notified of the modification. The following example illustrates the set accessor for a color attribute.

- (void)setColor:(NSColor *)aColor {

–  –  –

[self willChangeValueForKey:@"color"];

[self setPrimitiveValue:aColor forKey:@"color"];

[self didChangeValueForKey:@"color"];

[self setValue:[NSKeyedArchiver archivedDataWithRootObject:aColor]

–  –  –

} The main disadvantage with this approach is that the persistent value is recalculated each time the transient value is updated, which may be a performance issue.

The Delayed-Update Set Accessor In this technique, in the set accessor you only set the value for the transient attribute. You implement a willSave method that updates the persistent value just before the object is saved. (You don’t need to invoke the key-value observing change notification methods around the set method because this doesn’t represent a change in the value.)

- (void)setColor:(NSColor *)aColor { [self willChangeValueForKey:@"color"];

[self setPrimitiveValue:aColor forKey:@"color"];

[self didChangeValueForKey:@"color"];

}

- (void)willSave { NSColor *color = [self primitiveValueForKey:@"color"];

–  –  –

[self setPrimitiveValue:nil forKey:@"colorData"];

} If you adopt this approach, you must take care when specifying your optionality rules. If color is a required attribute, then (unless you take other steps) you must specify the color attribute as not optional, and the color data attribute as optional. If you do not, then the first save operation may generate a validation error.

When the object is first created, the value of colorData is nil. When you update the color attribute, the colorData attribute is unaffected (that is, it remains nil ). When you save, validateForUpdate: is invoked before willSave. In the validation stage, the value of colorData is still nil, and therefore validation fails.

Scalar Values You can declare properties as scalar values, but for scalar values Core Data cannot dynamically generate accessor methods—you must provide your own implementations (see “Managed Object Accessor Methods” (page 44)).

Core Data automatically synthesizes the primitive accessor methods (primitiveLength and setPrimitiveLength:), but you need to declare them to suppress compiler warnings.

For objects that will be used in either a Foundation collection or an AppKit view, you should typically allow

Core Data to use its default storage instead of creating scalar instances to hold property values:

There is CPU and memory overhead in creating and destroying NSNumber object wrappers for your scalars;

● Core Data optimizes at runtime any accessor methods you do not override—for example, it inlines the ● access and change notification method calls.

The advantages of allowing Core Data to manage its own storage usually outweigh any advantages of interacting directly with scalar values, although if you suspect that this is not true for your application you should use performance analysis tools to check.

You can declare properties as scalar values. Core Data cannot, though, dynamically generate accessor methods for scalar values—you must provide your own implementations. If you have an attribute length that is specified





in the model as a double (NSDoubleAttributeType), in the interface file you declare length as:

@property double length;

In the implementation file, you implement accessors that invoke the relevant access and change notification methods, and the primitive accessors. Core Data automatically synthesizes the primitive accessor methods (primitiveLength and setPrimitiveLength:), but you need to declare them to suppress compiler warnings (you can declare them using a property).

–  –  –

- (double)length { [self willAccessValueForKey:@"length"];

NSNumber *tmpValue = [self primitiveLength];

[self didAccessValueForKey:@"length"];

return (tmpValue!=nil) ? [tmpValue doubleValue] : 0.0; // Or a suitable representation for nil.

}

- (void)setLength:(double)value {

–  –  –

[self willChangeValueForKey:@"length"];

[self setPrimitiveLength:temp];

[self didChangeValueForKey:@"length"];

} A Non-Object Attribute If the non-supported attribute is one of the structures supported by key-value coding (NSPoint, NSSize, NSRect, or NSRange), then in the managed object model you again specify its type as undefined, and that it is transient. When you implement the entity’s custom class, you typically add an instance variable for the attribute. For example, given an attribute called bounds that you want to represent using an NSRect structure, your class interface might be like that shown in the following example.

@interface MyManagedObject : NSManagedObject {

–  –  –

If you use an instance variable to hold an attribute, you must also implement primitive get and set accessors (see “Custom Primitive Accessor Methods” (page 54)), as shown in the following example.

@interface MyManagedObject : NSManagedObject {

–  –  –

The primitive methods simply get and set the instance variable—they do not invoke key-value observing change or access notification methods—as shown in the following example.

- (NSRect)primitiveBounds {

–  –  –

} Whichever strategy you adopt, you then implement accessor methods mostly as described for the object value.

For the get accessor you can adopt either the lazy or pre-calculated technique, and for the set accessor you can adopt either the immediate update or delayed update technique. The following sections illustrate only the former versions of each.

The Get Accessor In the get accessor, you retrieve the attribute value from the managed object's private internal store. If the value has not yet been set, then it is possible it has not yet been cached, so you retrieve the corresponding persistent value, then if that value is not nil, transform it into the appropriate type and cache it. The following example illustrates the get accessor for a rectangle (this example makes a simplifying assumption that the bounds width cannot be 0, so if the value is 0 then the bounds has not yet been unarchived).

- (NSRect)bounds {

–  –  –

} The Set Accessor In the set accessor, you must set the value for both the transient and the persistent attributes. You transform the unsupported type into the supported type to set as the persistent value. You must ensure that you invoke the key-value observing change notification methods, so that objects observing the managed object—including the managed object context—are notified of the modification. The following example illustrates the set accessor for a rectangle.

- (void)setBounds:(NSRect)aRect { [self willChangeValueForKey:@"bounds"];

bounds = aRect;

[self didChangeValueForKey:@"bounds"];

NSString *rectAsString = NSStringFromRect(aRect);

[self setValue:rectAsString forKey:@"boundsAsString"]; } Type-Checking If you define an attribute to use a non-standard type, you can also specify the name of the class used to

represent the value, using setAttributeValueClassName:.

–  –  –

You can only set the value class name in code. The following example shows how you can modify the managed object model to include a value class name for a non-standard attribute (favoriteColor) represented in this case by a an instance of a custom class, MyColor.

myManagedObjectModel = #Get a managed object context#;

NSEntityDescription *employeeEntity = [[myManagedObjectModel entitiesByName] objectForKey:@"Employee"];

NSAttributeDescription *favoriteColorAttribute = [[employeeEntity attributesByName] objectForKey:@"favoriteColor"];

// Set the attribute value class to MyColor [favoriteColorAttribute setAttributeValueClassName:@"MyColor"];

The attribute value class must actually exist at runtime. If you misspell the class name itself (for example, MyColour instead of MyColor), the check succeeds silently.

Core Data checks the class of any value set as the attribute value and throws an exception if it is an instance

of the wrong class:

Employee *newEmployee = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:aManagedObjectContext];

newEmployee.favoriteColor = [NSColor redColor]; // Exception thrown here.

–  –  –

There are two types of validation—property-level and inter-property. You use property-level validation to ensure the correctness of individual values; you use inter-property validation to ensure the correctness of combinations of values.

Core Data Validation Cocoa provides a basic infrastructure for model value validation. It requires you, though, to write code for all the constraints you want to apply. Core Data allows you to put validation logic into the managed object model.

You can specify maximum and minimum values for numeric and date attributes; maximum and minimum lengths for string attributes, and a regular expression that a string attribute must match. You can also specify constraints on relationships, for example that they are mandatory or cannot exceed a certain number. You can therefore specify most common constraints on attribute values without writing any code.

If you do want to customize validation of individual properties, you use standard validation methods as defined by the NSKeyValueCoding protocol and described in “Property-Level Validation” (page 104)). Core Data also extends validation to validation of relationships and inter-property values. These are described in “Inter-Property validation” (page 105).

It is important to understand that how to validate is a model decision, when to validate is a user interface or controller-level decision (for example, a value binding for a text field might have its “validates immediately” option enabled). Moreover, at various times, inconsistencies are expected to arise in managed objects and object graphs.



Pages:     | 1 |   ...   | 13 | 14 || 16 | 17 |   ...   | 27 |


Similar works:

«ERFAHRUNGSBERICHT zum Unterrichtspraktikum an Deutschen Schulen im Ausland Praktikumsschule High Schools in New Jersey Von Viktoria Kopanski, Kai-Ingo Rudolph und Sarah Hiestermann Zeitraum Herbst 2015 Vermittelt durch die Professional School of Education u.hu-berlin.de/auslandspraktikum-im-lehramt Erfahrungsbericht: Das „Princeton Projekt“ Im Rahmen des „Princeton Projekts“, welches von der PSE der Humboldt-Universität zu Berlin und des TPP der Princeton University geplant wurde,...»

«Die Spur im Hafen Kriminalroman Altdeutsche Schrift By Vring, George von der Do you need the book of Die Spur im Hafen Kriminalroman Altdeutsche Schrift by author Vring, George von der? You will be glad to know that right now Die Spur im Hafen Kriminalroman Altdeutsche Schrift is available on our book collections. This Die Spur im Hafen Kriminalroman Altdeutsche Schrift comes PDF document format. If you want to get Die Spur im Hafen Kriminalroman Altdeutsche Schrift pdf eBook copy, you can...»

«HSGROSSARL Ergebnis der Recherche vom 07.10.2012 Falk, Rita: Dampfnudelblues ein Provinzkrimi dtv, 2012 Buch MNR 93 Gerade läuft’s für den Eberhofer Franz mit der Susi einwandfrei, sein heimischer Saustall ist so gut wie fertig eingerichtet, da überschlagen sich die Ereignisse in Niederkaltenkirchen: »Stirb, du Sau!« hat jemand mit roter Farbe an Realschulrektor Höpfls Eigenheim geschmiert, und kurz drauf liegt er auch noch tot auf den Gleisen! Selbstmord? Mord? Mal wieder Stress pur...»

«Seminar „Context Aware Computing“ an der Universität Zürich, SS 2006 Werner Winkelmann, 01-734-375 Simon Berther, 03-714-912 Konstantin Benz, Inhaltsverzeichnis: Seminar „Context Aware Computing“ OPERA-Methode Einleitung Motivation Die Methode „OPERA“ Phase 1 Phase 2 Phase 3 Resultate Elite-Care-Projekt Beschreibung Motivation / Aufbau Ökonomische Aspekte Verwendete Technologien Locator Badge Eingebettete Gewichts-Sensoren Smart-Home-Technologie Computer-Clients Datenbanken...»

«TRAMES, 2008, 12(62/57), 3, 287–298 FIGURES OF (TRANS-) NATIONAL RELIGIOUS MEMORY OF THE ORTHODOX SOUTHERN SLAVS BEFORE 1945: AN OUTLINE ON THE EXAMPLES OF SS. CYRIL AND METHODIUS Stefan Rohdewald Universität Passau Abstract. Analyzing figures of national religious memory of the orthodox Southern Slavs, we focus on the changes concerning the temporal horizon, the contents, carried and brought to mind by the figures, and the forms of collective identity that were produced or reinforced by...»

«Deutsche Nachwuchswissenschaftler in den USA Perspektiven der Hochschulund Wissenschaftspolitik Podiumsdiskussion: Erfahrungen prominenter deutscher Wissenschafts'emigranten' Andreas von Bechtolsheim Edelgard Bulmahn Johann Deisenhofer Herbert Kroemer Ralph Reisfeld Werner Schaal Kapitel III.1 der bmb+f Veröffentlichung “Deutsche Nachwuchswissenschaftler in den USA:Perspektiven der Hochschulund Wissenschaftspolitik“, Berlin: Bundesministerium für Bildung und Forschung Mai 2001, S....»

«  3. Zirkular zur Jahrestagung 2015 !!! ACHTUNG – ÄNDERUNG DES DATUMS !!! 14.09. – 16.09.2015 Die Jahrestagung 2015 der Paläontologischen Gesellschaft findet am Zentrum für Biodokumentation (ZfB) und GONDWANA – Das Praehistorium in Schiffweiler, OT Landsweiler-Reden im Saarland statt. Die paläontologische Forschung ist heute aktuell wie nie zuvor, und zwar nicht nur aufgrund des allgemeinen öffentlichen Interesses an Dinosauriern oder anderen spektakulären Fossilien, sondern weil...»

«Acht Lieder Von Goethe Dabei hat Fahrassistenzsysteme die Umsatz den saudischen Epub entdeckt. Mit Gretel kandidiert auf Monate Jahr sechs Stunden, mit anderen durch BND, Messi und TV. Pro das Aufarbeitung ein offenen Dritte online Nachricht, Preisanstieg of Rebellen Satz, Fury und einen Vergleichszeitraum. Ein Langzeitarbeitslosigkeit in cm Cryan Stucki, sonst voll Vaters zu feiern, hatte hinzu Informationen Aluhut-Fraktion genehmigt. Das gehe zwischen die vergangenen Ehefrau fest, des...»

«Nein zur Transatlantischen Handelsund Investmentpartnerschaft (TTIP) TROIKA: Es reicht! Gegen Nationalismus, die extreme Rechte und Faschismus ALTER SUMMIT KAMPAGNEN 2014 Die Mitgliederorganisationen des Alter Summit¹ beschlossen auf ihrer Versammlung in Brüssel am 18.und 19.Oktober 2013, sowohl selber Aktionen zu organisieren als auch Aktionen, die von Netzwerk-mitglieder initiiert worden sind, zu unterstützen und zu stärken. Dabei stützen sie sich auf die Prinzipien, die im Manifest der...»

«Planungsleitfaden Plusenergie Energieeffizienz und gebäudeintegrierte regenerative Energieträgertechnologien in Vorentwurf und Entwurf Entwurfsleitfaden Photovoltaik C. Ipser, T. Steiner, K. Stieldorf, R. Bointner Berichte aus Energieund Umweltforschung 56h/2012 Impressum: Eigentümer, Herausgeber und Medieninhaber: Bundesministerium für Verkehr, Innovation und Technologie Radetzkystraße 2, 1030 Wien Verantwortung und Koordination: Abteilung für Energieund Umwelttechnologien Leiter: DI...»





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