Reputation: 2504
I have an NSManagedObject that has an attribute that I use only for ordering in an NSFetchedResultsController. The value of that attribute is determined from the values of other attributes or relationships.
Therefore I figure out its value when I am getting ready to save the object. It seems, from my reading of documentation and experimenting, that I can do this in either - (void) willSave
or - (BOOL) validateForUpdate: NSError **error
.
My experimenting shows me these are called in tandem, first validateForUpdate
then willSave
.
However, since my insight into what is happening behind the scenes is poor, I was wondering it anyone could advise if one place is better than the other to set the value and why?
Thanks.
Upvotes: 2
Views: 565
Reputation: 60140
You'd probably want to be in willSave
; you're not technically doing validation, and the discussion for the method makes reference to computing derived values.
Upvotes: 0
Reputation: 14549
if you have a derived value, you typically do not want to save it, but if you do want to save it (thus negating the advantage of dynamically generating it, but can be done for speed reasons if you have a lot of objects and want to do some fancy predicate work.) you can set it up in your model as a normal value then make a custom accessor that checks to see if the primitive value is set, with primitiveValueForKey:@"propertyName"
... something like
.h
@property()NSString* someProperty;
.m
@dynamic someProperty;
-(NSString *) someProperty
{
pValue = [self primitiveValueForKey;@"someProperty"];
if(!pValue)
{
//calculate pvalue
pValue = [self derivedPValue];
[self setPrimitiveValue: pValue forKey:@"someProperty"];
}
return pValue;
}
Upvotes: 1