FREE ELECTRONIC LIBRARY - Books, dissertations, abstract

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

There is nothing to disallow an in-memory object from becoming inconsistent on a temporary basis. The validation constraints are applied by Core Data only during a “save” operation or upon request (you can invoke the validation methods directly as and when you wish). Sometimes it may be useful to validate changes as soon as they are made and to report errors immediately. This can prevent the user being presented with a long list of errors when they finally come to save their work. If managed objects were required to be always in a valid state, it would amongst other things force a particular workflow on the end-user. This also underpins the idea of a managed object context representing a "scratch pad"—in general you can bring managed objects onto the scratch pad and edit them however you wish before ultimately either committing the changes or discarding them.

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

Managed Object Validation Property-Level Validation Property-Level Validation The NSKeyValueCoding protocol specifies a method—validateValue:forKey:error:—that provides general support for validation methods in a similar way to that in which valueForKey: provides support for accessor methods.

If you want to implement logic in addition to the constraints you provide in the managed object model, you should not override validateValue:forKey:error:. Instead you should implement methods of the form


Important: If you do implement custom validation methods, you should typically not invoke them directly.

Instead you should call validateValue:forKey:error: with the appropriate key. This ensures that any constraints defined in the managed object model are also applied.

In the method implementation, you check the proposed new value and if it does not fit your constraints you return NO. If the error parameter is not null, you also create an NSError object that describes the problem, as illustrated in this example.

-(BOOL)validateAge:(id *)ioValue error:(NSError **)outError {

–  –  –

NSDictionary *userInfoDict = @{ NSLocalizedDescriptionKey : errorStr };

NSError *error = [[NSError alloc] initWithDomain:EMPLOYEE_ERROR_DOMAIN

–  –  –

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

Managed Object Validation Inter-Property validation

–  –  –

} //...

The input value is a pointer to object reference (an id *). This means that in principle you can change the input value. Doing so is, however, strongly discouraged, as there are potentially serious issues with memory management (see “Key-Value Validation” in Key-Value Coding Programming Guide ). Moreover, you should not call validateValue:forKey:error: within custom property validation methods. If you do, you will create an infinite loop when validateValue:forKey:error: is invoked at runtime.

If you change the input value in a validateKey:error: method, you must ensure that you only change the value if it is invalid or uncoerced. The reason is that, since the object and context are now dirtied, Core Data may validate that key again later. If you keep performing a coercion in a validation method, this can therefore produce an infinite loop. Similarly, you should also be careful if you implement validation and willSave methods that produce mutations or side effects—Core Data will revalidate those changes until a stable state is reached.

Inter-Property validation It is possible for the values of all the individual attributes of an object to be valid and yet for the combination of values to be invalid. Consider, for example, an application that stores information about people including their age and whether or not they have a driving license. For a Person object, 12 might be a valid value for an age attribute, and YES is a valid value for a hasDrivingLicense attribute, but (in most countries at least) this combination of values would be invalid.

NSManagedObject provides additional opportunities for validation—update, insertion, and deletion—through the validateFor… methods such as validateForUpdate:. If you implement custom inter-property validation methods, you call the superclass’s implementation first to ensure that individual property validation methods are also invoked. If the superclass's implementation fails (that is, if there is an invalid attribute value), then you


1. Return NO and the error created by the superclass's implementation.

2. Continue to perform validation, looking for inconsistent combinations of values.

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

Managed Object Validation Inter-Property validation If you continue, you must make sure that any values you use in your logic are not themselves invalid in such a way that your code might itself cause errors (for example, if there is an attribute whose value is required to be greater than 0, which is actually 0 so fails validation but which you use as a divisor in a computation).

Moreover, if you discover further validation errors, you must combine them with the existing error and return a “multiple errors error” as described in “Combining Validation Errors” (page 108).

The following example shows the implementation of an inter-property validation method for a Person entity that has two attributes, birthday and hasDrivingLicense. The constraint is that a person aged less than 16 years cannot have a driving license. This constraint is checked in both validateForInsert: and validateForUpdate:, so the validation logic itself is factored into a separate method.

Listing 1 Inter-property validation for a Person entity

- (BOOL)validateForInsert:(NSError **)error { BOOL propertiesValid = [super validateForInsert:error];

–  –  –

BOOL consistencyValid = [self validateConsistency:error];

return (propertiesValid && consistencyValid);


- (BOOL)validateForUpdate:(NSError **)error { BOOL propertiesValid = [super validateForUpdate:error];

–  –  –

BOOL consistencyValid = [self validateConsistency:error];

return (propertiesValid && consistencyValid);


- (BOOL)validateConsistency:(NSError **)error {

–  –  –

gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

} NSDateComponents *components = [gregorianCalendar components:NSYearCalendarUnit

–  –  –

[userInfo setObject:drivingAgeErrorString forKey:NSLocalizedFailureReasonErrorKey];

[userInfo setObject:self forKey:NSValidationObjectErrorKey];

–  –  –

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

Managed Object Validation Combining Validation Errors

–  –  –

} } } Combining Validation Errors If there are multiple validation failures in a single operation, you create and return a "multiple errors error"—that is, an NSError object with the code NSValidationMultipleErrorsError. You add individual errors to an array and add the array—using the key NSDetailedErrorsKey—to the user info dictionary in the NSError object. This pattern also applies to errors returned by the superclass's validation method. Depending on how many tests you perform, it may be convenient to define a method that combines an existing NSError object (which may itself be a multiple errors error) with a new one and returns a new multiple errors error.

The following example shows the implementation of a simple method to combine two errors into a single multiple errors error. How the combination is made depends on whether or not the original error was itself a multiple errors error.

Listing 2 A method for combining two errors into a single multiple errors error

- (NSError *)errorFromOriginalError:(NSError *)originalError error:(NSError *)secondError { NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];

NSMutableArray *errors = [NSMutableArray arrayWithObject:secondError];

–  –  –

if ([originalError code] == NSValidationMultipleErrorsError) { [userInfo addEntriesFromDictionary:[originalError userInfo]];

[errors addObjectsFromArray:[userInfo objectForKey:NSDetailedErrorsKey]];

Faulting is a mechanism Core Data employs to reduce your application’s memory usage. A related feature called uniquing ensures that, in a given managed object context, you never have more than one managed object to represent a given record.

Faulting Limits the Size of the Object Graph Faulting reduces the amount of memory your application consumes. A fault is a placeholder object that represents a managed object that has not yet been fully realized, or a collection object that represents a


A managed object fault is an instance of the appropriate class, but its persistent variables are not yet ● initialized.

A relationship fault is a subclass of the collection class that represents the relationship.

● Faulting allows Core Data to put boundaries on the object graph. Because a fault is not realized, a managed object fault consumes less memory, and managed objects related to a fault are not required to be represented in memory at all.

To illustrate, consider an application that allows a user to fetch and edit details about a single employee. The employee has a relationship to a manager and to a department, and these objects in turn have other relationships. If you retrieve just a single Employee object from a persistent store, its manager, department, and reports relationships are initially represented by faults. Figure 1 shows an employee’s department relationship represented by a fault.

Figure 1 A department represented by a fault

–  –  –

Although the fault is an instance of the Department class, it has not yet been realized—none of its persistent instance variables have yet been set. This means that not only does the department object consume less memory itself, but there’s no need to populate its employees relationship. If it were a requirement that the object graph be complete, then to edit a single attribute of a single employee, it would ultimately be necessary to create objects to represent the whole corporate structure.

Fault handling is transparent—you do not have to execute a fetch to realize a fault. If at some stage a persistent property of a fault object is accessed, then Core Data automatically retrieves the data for the object and initializes the object (see NSManagedObject Class Reference for a list of methods that do not cause faults to fire). This process is commonly referred to as firing the fault. If you send the Department object a message to get, say, its name, then the fault fires—and in this situation Core Data executes a fetch for you to retrieve all the object's attributes.

Firing Faults Core Data automatically fires faults when necessary (when a persistent property of a fault is accessed). However, firing faults individually can be inefficient, and there are better strategies for getting data from the persistent store (see “Batch Faulting and Pre-fetching with the SQLite Store” (page 142)). For more about how to efficiently deal with faults and relationships, see “Fetching Managed Objects” (page 141).

When a fault is fired, Core Data does not go back to the store if the data is available in its cache. With a cache hit, converting a fault into a realized managed object is very fast—it is basically the same as normal instantiation of a managed object. If the data is not available in the cache, Core Data automatically executes a fetch for the fault object; this results in a round trip to the persistent store to fetch the data, and again the data is cached in memory.

Pages:     | 1 |   ...   | 14 | 15 || 17 | 18 |   ...   | 27 |

Similar works:

«February 2013 The President’s Emergency Plan for AIDS Relief NEXT GENERATION Planning and Reporting INDICATORS REFERENCE GUIDE Version 1.2 February 2013 Table of Contents INTRODUCTION Background 4 PEPFAR Next Generation Indicators-Directional Shifts 5 Move from Downstream/Upstream to Direct/National 9 Indicator Classifications & Definitions 10 Utilizing the Concept of Applicability 15 Strategies for the Collections of Outcome and Impact Indicators 17 INDICATOR SUMMARY TABLES Table 1: PEPFAR...»

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

«Fachbereich 4: Informatik takomat GmbH Glaubwürdige automatische Gesichtsanimation auf Basis aufgenommener Sprache Bachelorarbeit zur Erlangung des Grades eines Bachelor of Science (B.Sc.) im Studiengang Computervisualistik vorgelegt von Philipp Mungenast Erstgutachter: Dipl. Inf. Martin Stöcker takomat GmbH Zweitgutachter: Prof. Dr. Stefan Müller Institut für Computervisualistik, Universität Koblenz-Landau Koblenz, im April 2010 Erklärung Ich versichere, dass ich die vorliegende Arbeit...»

«DATA CENTER Encryption Solution Design and Deployment Considerations This Encryption Solution Design and Deployment Considerations reference guide is designed to help customers and partners architect and deploy Brocade encryption solutions to maximize system performance, minimize administrative overhead, and mitigate the possibility of operational disruptions. This guide was compiled with the help of a working group of subject matter experts from Brocade Headquarters and the Brocade field...»


«Gesundheitliche und ökologische Aspekte mobiler Telekommunikation – Wissenschaftlicher Diskurs, Regulierung und öffentliche Debatte Franz Büllingen Annette Hillebrand Nr. 246 Juli 2003 wik Wissenschaftliches Institut für Kommunikationsdienste GmbH Rhöndorfer Str. 68, 53604 Bad Honnef Postfach 20 00, 53588 Bad Honnef Tel 02224-9225-0 Fax 02224-9225-66 Internet: http://www.wik.org eMail info@wik.org In den vom WIK herausgegebenen Diskussionsbeiträgen erscheinen in loser Folge Aufsätze...»

«United States DATE: June 5, 2007 Department of Agriculture TO: Board of Directors Federal Crop Federal Crop Insurance Corporation Insurance Corporation FROM: Eldon Gould /signed/ 1400 Independence Manager Avenue, SW Stop 0801 Washington, DC SUBJECT: Manager’s Report 20250-0801 Exhibit No. 2899 This memorandum serves as the Manager’s Report to the Board of Directors (Board), Federal Crop Insurance Corporation (FCIC), for the June 5, 2007 meeting. The report relates to program issues as...»

«Kenkmann, Andrea Adapting and designing spaces: children and their schools CEPS Journal 1 (2011) 2, S. 11-24 Empfohlene Zitierung/ Suggested Citation: Kenkmann, Andrea: Adapting and designing spaces: children and their schools In: CEPS Journal 1 (2011) 2, S. 11-24 URN: urn:nbn:de:0111-opus-60683 in Kooperation mit / in cooperation with: http://www.pef.uni-lj.si Nutzungsbedingungen Terms of use Gewährt wird ein nicht exklusives, nicht übertragbares, persönliches We grant a non-exclusive,...»

«Veröffentlichungsliste 1E. C. Paloura, A. Knop, U. Döbler, K. Holldack und S. Logothetidis On the contribution of a nitrogen-related defect in the NEXAFS spectra of thin Si3N4 films in MRS Boston 1992 Proceedings, Hg.: J. Kanicki, W. L. Warren, R. A. B. Devine und M. Matsumura, 284 (1992) 107 2E. C. Paloura, A. Knop, K. Holldack, U. Döbler und S. Logothetidis On the identification of N dangling bonds in SiN films using X-ray absorption studies J. Appl. Phys. 73 (1993) 2995 3A. Markwitz, H....»

«DE VERANTWOORDELIJKHEID VAN DE COMMISSIONAIR-EXPEDITEUR TEGENOVER DE COMMITTENT door Andre D'HALLUIN Gustaaf HUYBRECHS Inleiding DE COMMISSIONAIR-EXPEDITEUR ALS HANDELSTUSSENPERSOON 1. De comrnissionair-expediteur (forwarding agent) hoort thuis bij de reeks tussenpersonen in het handelsverkeer. Hij is de architekt van de transportverrichtingen. Voor rekening van de committent sluit hij in eigen naam aile contracten die nodig zijn voor het vervoer van de goederen. Als expert op een specifiek...»

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