Class not setting as expected
Icon is set as @property (nonatomic, retain) AHGridIcon *icon;
Usually i just do:
-(void)setIcon:(AHGridIcon *)iconLocal {
icon = iconLocal;
}
But i read a guide to getters setters and properties online which has lead me to be开发者_开发百科lieve that instead, this is right:
-(void)setIcon:(AHGridIcon *)iconLocal {
if (iconLocal != self.icon)
{
NSLog(@"local: %@", iconLocal);
NSLog(@"self.icon 1: %@", self.icon);
[iconLocal retain];
[icon release];
icon = iconLocal;
NSLog(@"self.icon 2: %@", self.icon);
}
}
The problem is, the original icon is staying put, it's not being replaced with the new icon. What am i doing wrong? Should i just revert to the usual way i do it?
You should use '@synthesize' unless you really need custom setter behavior.
like I posted in my comment:
the best way is to use @synthesize
which will create a getter and a setter to with respect to the properties you wrote in your property (nonatomic, retain)
=> not threadsafe but fast getter and setter and a retaining (and also releasing) setter. If you dont need sophisticating stuff to do in your setter then you should not override the setter.
.h:
@property (nonatomic, retain) AHGridIcon *icon;
.m:
@implementation Something
@synthesize icon;
...
@end
The code you posted in your setter is nearly the same as the compiler would produce when only using synthesize.
Your usual way is not really nice because in your header is defined (in your property) that the setter is retaining but in your implementation you are overriding that correct setter which doesn't retain. It is nearly the same as the compiler would produce with an (nonatomic, assign) property.
But if you want to override your setter then it should look like the same as you wrote. For me it is working fine.
- first retaining the new object
- then releasing the old one
- then assigning the local pointer to your new object
you can even omit your if but then it is really important that you first retain the new and then release the old objects (like you did - just want to mention that).
For solving your problem with an overriten setter: Your setter looks ok in my eyes. Have you also overriten the getter? If yes then post it here (you use it by calling self.icon in your log-call).
I've done a small test-program
@synthesize str;
- (void)setStr:(NSString *)localStr
{
if(str != localStr)
{
NSLog(@"old : %@", self.str);
NSLog(@"new1: %@", localStr);
[localStr retain];
[str release];
str = localStr;
NSLog(@"new2: %@", self.str);
}
}
and the output is fine:
old : (null)
new1: Hello
new2: Hello
old : Hello
new1: World
new2: World
精彩评论