Dan2552
Dan2552

Reputation: 1264

Overriding property setter in a class category

I've got an NSManagedObject class that I want to override a setter to but I've been told it's good practice to not modify the automatically generated class file and create categories to instead extend them (because if you change the model and regenerate the file, you lose all your additions).

If I make a method for the setter in a category, it definitely runs the method (tested with NSLog), but I don't know how to assign the actual property value. Normally, I'd synthesise the property using

@synthesize finished = _finished;

so that I can access the property in the setter using _finished, like so:

- (void)setFinished:(NSNumber *)finishedValue {
    _finished = finishedValue;
    self.end_time = [NSDate date];
}

but where the property is defined in the NSManagedObject this doesn't seem possible.

Upvotes: 6

Views: 3997

Answers (3)

Ryan Yan
Ryan Yan

Reputation: 590

There is an easy way to do so, try the following:

Model.h

@interface Model
@property(nonatomic,copy) NSString  * string;
@end

Model + Override.m

@interface Model ()
{
    NSString *_string;
} 
@end

@implementation Model (Override) 
- (void)setString:(NSString *)string
{
    return _string = string;
}    
@end

Upvotes: 0

jithinroy
jithinroy

Reputation: 1885

You can do with subclassing see the doc here

- (void)setName:(NSString *)newName
{
    [self willChangeValueForKey:@"name"];
    [self setPrimitiveName:newName];
    [self didChangeValueForKey:@"name"];
}

Upvotes: 8

Mr Bonjour
Mr Bonjour

Reputation: 3400

In a category, you can't add property value, only methods. So you will need to subClass in order to perform what you want.

Upvotes: 1

Related Questions