Reputation:
I know this is a newbie question but i can't get my head around this (or really, i can't get it working)
so i have in my .h
@interface
NSString *test;
@end;
@property NSString *test
and in my .m
...
@synthesize test;
...
but i want a custom setter for test - what is the correct syntax?
thanks
Upvotes: 1
Views: 2440
Reputation: 726987
First, you do not need to declare a variable test
if you plan to @synthesize
, but if you do, you need to put it in curly braces.
Second, the declaration of the property needs to be inside the interface:
@interface {
NSString *test;
}
@property (readwrite) NSString *test
@end;
Finally, the syntax for the setter is
-(void)setTest:(NSString*)test {
...
}
If you choose to override the getter as well, the convention is
-(NSString*)test {
return test;
}
Upvotes: 2
Reputation: 95365
If your custom setter has a method name that is different to setTest:
(assuming the property name is test
), you can specify the setter using:
@property(readwrite,setter=setShokolokobangoshay:) NSString *test;
Then if you have:
object.test = @"SomeValue";
It will automatically “translate” to:
[object setShokolokobangoshay:@"SomeValue"];
Otherwise, you can simply provide a setTest:
method and it will automatically be used as the setter for the property, even if you use the @synthesize
directive (in which case, the @synthesize
directive will only implement a getter).
Upvotes: 1
Reputation: 1910
Simple create a method with the definition
- (void) setTest:(NSString*) new_value
This is the method that will be called when you attempt to modify the value of the test property (you can alter this as appropriate for other property names).
Remember that this method will only be called when you attempt to modify self.test (the property) - if you modify the test variable directly, this will not call setTest. It's good practise to name your non-property variable something else (preceding with an underscore _test
is common), and have your synthesize statement refer to it:
@synthesize test = _test;
This will have accessing self.test get the value of _test, and modifying self.test call your setTest method. If you want to override the getter, this has the definition
- (NSString*) test
Upvotes: 1