How to provide additional custom implementation of accessor methods when using @synthesize?
accessor, cocoa, cocoa-touch, objective-c
Solution
You can use `@property` and `@synthesize` just like you normally would, but provide a custom setter or getter (or both) and those will be used instead. Typically I will do something like this:
// Override the setter
- (void)setName:(NSString *)aName
{
if (name == aName)
return;
[name release];
name = [aName retain];
//custom code here
}
When I use the set property, it will invoke my custom method. However, the get will still be synthesized.
Problem
I want to fire some code when a property is accessed and changed. I use `@property` and `@synthesize` in my code for my ivars. The properties are retained, so I'd like to keep that memory management stuff automatically generated by `@synthesize`. However, I assume that `@synthesize` tells the compiler to generate the accessor methods code right where `@synthesize is`, so most of the cases at the top of the code, right? And when I have a property `foo`, I get `-setFoo` and `-foo` methods. Could I then just make a method like this, to execute some more custom code when a property is changed? ``` -(void)setFoo { // custom stuff } ``` Now that's a problem. How to execute the first one? I wouldn't love to have a different name here. Is there maybe a way to let the `@synthesize` directive create other names for getter and setter methods, which I then call easily? And I would still be able to use the dot syntax then to access them?