4 ms·
This: - (void) setFoo:(NSString*) bar { [foo release]; foo = [bar retain]; } should be: - (void) setFoo:(NSString*) bar { if(bar == foo)
by tylerc230 15y ago
This:
- (void) setFoo:(NSString*) bar {
[foo release];
foo = [bar retain];
}
should be:
- (void) setFoo:(NSString*) bar {
if(bar == foo)
return;
[foo release];
foo = [bar retain];
}
so that you can do without crashing:
obj.foo = obj.foo;
- hrktb 15y agoIn the same line of thinking, for object that don't hold memory space I need to mark on the spot, I use : - (void) setFoo:(NSString*) bar { [foo autorelease]; foo = [bar retain]; } which I expect to do nothing (retain count is unchanged) when foo == bar. I do it for concision, am I missing something?
- azsromej 15y agothat works fine too and prevents any issues with releasing the variable before it gets retained again. objects might hang around in memory a little longer this way, though (for foos != bars)
- tylerc230 15y agoThat would also work, autorelease is generally considered slow though.
- pshc 15y agoThe cleanest version IMO is - (void) setFoo:(NSString*)bar { [bar retain]; [foo release]; foo = bar; } which harmlessly increments and decrements for self-assignment.
- andrewljohnson 15y agoAh, trickier than I thought. I posted an EDIT to the blog post.