I enabled zombies with my Xcode to find if my process crashes to a memory leak. Here is a code snippet:
- (NSString *)facVersion
{
return facVersion;
}
- (void) setFacVersion:(NSString*)_facVersion
{
if(facVersion != nil) [facVersion release];
facVersion = [_facVersion retain];
}
Now when I call
NSLog(@"%@", facVersion);
[self setFacVersion:facVersion];
the code crashes with the message
[CFString retain]: message sent to deallocated
Do you know what the problem is?
This is a typical problem with badly written setters. When the object itself is the last owner of the backing ivar of the property, assigning the property to itself causes a release effectively deallocating the object, then a retain on the same deallocated object. You can fix this in two ways. Either check for the to-be-assigned object not being the same as the current value of the property, or retain first and release only after. All in all, solution one:
Soltion two:
By the way, checking for an object not being
nilbefore releasing it is superfluous. Objective-C is not Java.