iOS CoreData primitive accessor

 

 

 

  Given an entity with an attribute firstName, Core Data automatically generates firstName, setFirstName:, primitiveFirstName, and setPrimitiveFirstName.

 

  The primary use of primitive accessors is to prevent key-value observing notifications from being sent when you change a value.

  Sometimes you do not want such notifications sent because they have quite a bit of overhead. E.g. when importing large sets of data or when you use a transitory value to alter a persisted value.

 

 


 

 

 

  In my opinion,

  You could override the awakeFromInsert method to set a default value for this property;

  Every time you insert object into managedObjectContext,

  CoreData framework will call awakeFromInsert method automatically.

  And in this method,you should use primitive accssor to set the default value.

 

  For example,there is a property dueDate in the category's .h file,

  u can define primitiveDueDate property in the subclass of NSManagedObject.

  And add @dynamic primitiveDueDate in .m file.

 

 

   show u the code:

 

// a subclass of NSManagedObject

//.h file
@interface Task : NSManagedObject

@property (nonatomic, strong) NSDate *primitiveDueDate;

@end

//.m file
@implementation Task

@dynamic primitiveDueDate;

- (void)awakeFromInsert{
    [super awakeFromInsert];
    
    NSDate *defaultDate = [NSDate dateWithTimeIntervalSinceNow:60*60*24*3]; // 3 days
    
    self.primitiveDueDate = defaultDate;
}

@end

// category file contains a property named dueDate

@interface Task (CoreDataProperties)

@property (nullable, nonatomic, retain) NSDate *dueDate;

@end

 

 

 

 

 

References:

http://stackoverflow.com/questions/5509106/why-would-i-need-to-use-a-primitive-accessor-methods-in-a-core-data-project

http://stackoverflow.com/questions/7427373/what-are-the-primitive-accessors-for-in-core-data

 

 

Caution (infinite loop):

http://stackoverflow.com/questions/14150654/kvo-core-data-and-primitive-accessors

 

posted @ 2016-08-10 16:40  Ficow  阅读(242)  评论(0编辑  收藏  举报