Learn Objective-C on the Mac - Mark Dalrymple [80]
The Obligatory Dealloc Method
Finally, the last method is a simple dealloc, shown here:
No surprises here. This is the standard way to release instance variables in a dealloc method. However, keep in mind that in an app using garbage collection, the dealloc method is never actually called.
Adding Business Logic
Now that you’ve seen the basic idea of constructing an application with Core Data, including defining the model, configuring the GUI, and knowing your way around the template-provided code in your project, it’s time to learn a bit about how to use Core Data to actually implement something “interesting” in your model objects: Your application’s “business logic.”
Some amount of business logic is specified right in the model file, such as an integer’s min and max size, while some things require a bit of code. Fortunately NSManagedObject provides several “hooks” into spots where you can test your objects’ attributes to validate them and make sure they’re okay.
Validating Single Attributes
Let’s say we want to add a special constraint to MythBase to ensure that no MythicalPerson can be named “Bob.” To do this, we just have to add the method shown here to the @implementation section of MythicalPerson.m:
Note the name of this method, validateName:error:. Attribute validation in Core Data works through the use of methods named validate At this point, you can compile and run MythBase, and everything will work the same as before, up until you change a MythicalPerson’s name to “Bob” and try to save your changes, at which point you’ll be warned that it’s an invalid value. Validating Multiple Attributes These methods both work in the same way. First, they call the superclass’s version of the same method; that’s very important, because that’s the method that actually calls all of the validate Now let’s see what validateConsistency: looks like: Be sure to enter that method somewhere above the validateForInsert:
Sometimes, you’ll need to be able to validate several attributes at once, making sure that they make sense together. For example, let’s say that we decide on a new constraint for each MythicalPerson: the value of the power attribute can only exceed 50 if the value of the divinity attribute is 100 (meaning that only a person operating in full “god mode” can have a power level above 50). Rather than check for this condition in validatePower:error: or validateDivinity:error:, the recommended procedure is to check for this in two other validation methods that are called whenever a new managed object is created, or edited: validateForInsert:, and validateForUpdate:. Because we’re going to check for the same internal consistency problem (where power > 50 and divinity < 100) in both spots, we’ll put that check into a method of our own, validateConsistency:, which is called by the other two. First, let’s implement the two Core Data validation methods: