Setters in Cocoa

Which of the three setters is better:

[objc gutter=”false”]
– (void)setName:(NSString*)value{
if(value != name){
[name release];
name = [value retain];
}
}

– (void)setName:(NSString*)value{
id old = name;
name = [value retain];
[old release];
}

– (void)setName:(NSString*)value{
[name autorelease];
name = [value retain];
}
[/objc]

Personally I’d use the third variant, but I’m open to suggestions 🙂

3 comments on Setters in Cocoa

  1. The second one is the most efficient as most of the times the new value differs from the old one, which gets us to the point of comparing the speed of an if vs. an assignment.

  2. Cristian, I’m not sure if the speed comparison between an if statement and an assignment one will provide different results.

Leave a Reply

Your email address will not be published. Required fields are marked *