我需要在setter方法中做一些额外的事情。但是这样做我得到一个无限循环:
我有一个核心数据对象
@interface Transaction : NSManagedObject
@property (nonatomic, retain) NSDate * date;
@end
@implementation Transaction
@dynamic date;
-(void)setDate:(NSDate *)date
{
self.date = date;
//additional stuff omitted
}
所以,在这种情况下,我得到一个无限循环。好的,所以我在网上搜索并按以下方式修改我的代码,并且每个版本都会出现编译错误
版本1:
@interface Transaction : NSManagedObject
@property (nonatomic, retain) NSDate * date;
@end
@implementation Transaction
@dynamic date;
-(void)setDate:(NSDate *)date
{
self->date = date; //Error: Property 'date' found on object 'Transaction *'; did you mean to access it with the "." operator?
//additional stuff omitted
}
第2版:
@interface Transaction : NSManagedObject
@property (nonatomic, retain) NSDate * date;
@end
@implementation Transaction
@dynamic date = _date; //Error: Expected ';' after @dynamic
-(void)setDate:(NSDate *)date
{
_date = date;
//additional stuff omitted
}
现在,我问自己该怎么做?
答案 0 :(得分:5)
我的问题的解决方案:
@interface Transaction : NSManagedObject
@property (nonatomic, retain) NSDate * date;
@end
@implementation Transaction
@dynamic date;
-(void)setDate:(NSDate *)date
{
[self setPrimitiveValue:date forKey:@"date"];
//additional stuff omitted
}
答案 1 :(得分:2)
“日期”是否由Core Data中的相应属性支持?
如果是,请查看Custom setter methods in Core-Data
如果没有,并且您不需要保留“日期”,则您的代码应如下所示:
@interface Transaction : NSManagedObject
@property (nonatomic, retain) NSDate * date;
@end
@implementation Transaction
@synthesize date = _date;
-(void)setDate:(NSDate *)date
{
_date = date;
//additional stuff omitted
}
答案 2 :(得分:1)
以下是用于在不破坏KVO的情况下覆盖NSManagedObject属性的Apple方法:.m:
@interface Transaction (DynamicAccessors)
- (void)managedObjectOriginal_setDate:(NSDate *)date;
@end
@implementation Transaction
@dynamic date;
- (void)setDate:(NSDate *)date
{
[self managedObjectOriginal_setDate:(NSString *)date;
// your custom code
}
如本页底部What's New in Core Data in macOS 10.12, iOS 10.0, tvOS 10.0, and watchOS 3.0
所示