6

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.

Dan2552
  • 1,244
  • 1
  • 15
  • 26
  • You get an error saying you cannot synthesize in a category – Dan2552 Oct 29 '12 at 12:32
  • This doesn't answer the question, but gets you to where you're going in a different way: http://compileyouidontevenknowyou.blogspot.com/2012/06/adding-properties-to-class-you-dont.html – Dan Rosenstark Nov 20 '13 at 22:14

3 Answers3

8

You can do with subclassing see the doc here

- (void)setName:(NSString *)newName
{
    [self willChangeValueForKey:@"name"];
    [self setPrimitiveName:newName];
    [self didChangeValueForKey:@"name"];
}
jithinroy
  • 1,885
  • 1
  • 16
  • 23
  • 4
    Using `[self setPrimitiveValue:finished forKey:@"finished"]` appears to work in the category, that's what I was looking for, thanks for leading me in the right direction – Dan2552 Oct 29 '12 at 12:40
1

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

Mr Bonjour
  • 3,330
  • 2
  • 23
  • 46
  • you can, http://stackoverflow.com/questions/8733104/objective-c-property-instance-variable-in-category – someUser Jan 12 '16 at 01:31
0

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
Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85
Ryan Yan
  • 580
  • 5
  • 11