Overriding setters with arc and dynamic properties

喜欢而已 提交于 2020-01-14 14:56:09

问题


I need to do some additional stuff in a setter method. But I get an infinite loop when doing so:

I've got a core data object

@interface Transaction : NSManagedObject 
@property (nonatomic, retain) NSDate * date;
@end

@implementation Transaction
@dynamic date;

-(void)setDate:(NSDate *)date
{
    self.date = date;
    //additional stuff omitted
}

So, in that case I get an infinite loop. Okay so I searched on the net and modified my code in the following way and for every version I get compiler errors

Version 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
}

Version 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
}

Now, I'm asking myself how to do this?


回答1:


The solution to my problem:

@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
}



回答2:


Is "date" backed by a corresponding attribute in Core Data?

If so, please take a look at Custom setter methods in Core-Data

If not, and you don't need to persist "date", your code should be the following:

@interface Transaction : NSManagedObject 
@property (nonatomic, retain) NSDate * date;
@end

@implementation Transaction
@synthesize date = _date;

-(void)setDate:(NSDate *)date
{
    _date = date; 
    //additional stuff omitted
}



回答3:


Here is the Apple way for overriding NSManagedObject properties without breaking KVO, in your .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
}

As seen at bottom of this page What's New in Core Data in macOS 10.12, iOS 10.0, tvOS 10.0, and watchOS 3.0



来源:https://stackoverflow.com/questions/8545799/overriding-setters-with-arc-and-dynamic-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!