iOS CoreData primitive accessor

本文探讨了CoreData中原始访问器(primitive accessors)的主要用途及实现方式,特别是如何利用这些访问器来避免不必要的键值观察(KVO)通知开销,并提供了设置默认属性值的具体示例。

 

 

 

  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

 

转载于:https://www.cnblogs.com/ficow/p/5757355.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值