Reputation: 3999
I have one class called dog and another class called cat.
Dog has an variable, "name" declared with @property in the .h file.
In the cat class, I have set the name by using the command, myDog.name = "buster", after creating the variable "myDog" of type dog.
I would like to do additional operations when the name is set by overriding the set method normally created by the @synthesize command.
How can I do that? Thanks for the help!
Upvotes: 1
Views: 5433
Reputation: 29552
You cannot override (and call it within) a synthesized method from within the very same class.
You can however override it from a subclass (or rather: synthesize it in an abstract superclass).
If you simply want to perform additional (vs. different) operations upon property change I would use KVO by simply adding each dog as observer to its own "name"
property in -(id)init;
.
Edit:
There is a way to add additional logic to synthesized methods from within the same class:
Define a private intermediate property in a class extension.
I've attached source code for a class which uses synthesized properties and takes care(sic!) of keeping the dog's owner in sync with its own identity.
Dog.h:
#import <Foundation/Foundation.h>
@interface Dog : NSObject {
@private
NSString *name;
NSString *owner;
}
@property (nonatomic, readwrite, retain) NSString *name;
@property (nonatomic, readwrite, retain) NSString *owner;
@end
Dog.m:
#import "Dog.h"
@interface Dog ()
@property (nonatomic, readwrite, retain) NSString *primitiveName;
@end
@implementation Dog
@dynamic name;
@synthesize primitiveName = name;
@synthesize owner;
- (id)init {
if ((self = [super init])) {
name = @"Snowy";
owner = @"Tintin";
}
return self;
}
- (void)dealloc {
[super dealloc];
}
- (NSString *)name {
return self.primitiveName;
}
- (void)setName:(NSString *)aName {
self.primitiveName = aName;
if ([aName isEqualToString:@"Snoopy"]) {
self.owner = @"Charlie Brown";
}
else if ([aName isEqualToString:@"Snowy"]) {
self.owner = @"Tintin";
}
}
- (NSString *)description {
return [NSString stringWithFormat:@"<%@ name:'%@' owner:'%@'>", [self class], self.name, self.owner];
}
@end
Test:
Dog *dog = [[Dog alloc] init];
NSLog(@"%@", dog);
dog.name = @"Snoopy";
NSLog(@"%@", dog);
dog.name = @"Snowy";
NSLog(@"%@", dog);
Result:
<Dog name:'Snowy' owner:'Tintin'>
<Dog name:'Snoopy' owner:'Charlie Brown'>
<Dog name:'Snowy' owner:'Tintin'>
Upvotes: 1
Reputation: 80603
This has been pretty much answered on SO already - see Objective-C synthesize property name overriding for details. In particular, @Dev Kanchen's answer which includes example code.
Upvotes: 3
Reputation: 2859
All you have to do is leave the @synthesize then create whichever methods you want to be custom. Example:
In .h
@property(nonatomic, retain)NSString *Bob;
In .m
@synthesize bob;
-(void)setBob:(NSString *)bobValue{
[bobValue retain];
[bob release];
bob = bobValue;
//your custom stuffs here
}
Upvotes: 5