每当调用[managedObjectContext save:nil]
时,我希望能够在NSManagedObject上执行自定义保存更改。
self.colorRaw = [NSKeyedArchiver archivedDataWithRootObject:self.color];
保存在此实现中。有什么想法吗?
@interface Filter : NSManagedObject
//auto-generated accessor
@property (nonatomic, retain) NSData * colorRaw;
// custom accessor
@property (strong, nonatomic) UIColor * color;
@end
@implementation
- (UIColor *)color
{
UIColor * color;
if ((color = objc_getAssociatedObject(self, @selector(color)))) {
return color;
}
if (self.colorRaw.length) {
color = [NSKeyedUnarchiver unarchiveObjectWithData:self.colorRaw];
self.color = color;
return color;
}
return nil;
}
- (void)setColor:(UIColor *)color
{
objc_setAssociatedObject(self, @selector(color), color, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
答案 0 :(得分:0)
答案其实很简单。只需为密钥NSManagedObjectContextWillSaveNotification
按照文档
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(<#Selector name#>)
name: NSManagedObjectContextWillSaveNotification
object:<#A managed object context#>];