Search code examples
core-datansmanagedobjectnsmanagedobjectcontextsetter

Core Data check if property has never been set


Is there a way to check if a NSManagedObject property, for example a float NSNumber, which has a default value = 0, has already been set in the setter?

I tried something like this:

-(void)setQuantity:(NSNumber *)quantity {

if (self.quantity==nil)
   NSLog(@"Property never been set");
else
   NSLog(@"Property already set");

[self willChangeValueForKey:@"quantity"];    
[self setPrimitiveQuantity: quantity];    
[self didChangeValueForKey:@"quantita"];

}

But "quantity" is never nil because initialized with default value. Thanks!


Solution

  • If the attribute has a default value it has been set during initialization. You have 2 options:

    1. Mark the attribute as optional and don't provide a default value. You can check for nil.
    2. Make sure the default value is unique and check against that value to determine if it has been changed since initialization. E.g., for otherwise positive numbers, use -1.

    Caveat for 1.: make sure nowhere in your code the attribute is set to nil again.
    Caveat for 2.: make sure nowhere in your code the attribute is set to the unique value.