Hacker Timesnew | past | comments | ask | show | jobs | submitlogin

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;


In 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?


The cleanest version IMO is

  - (void) setFoo:(NSString*)bar {
    [bar retain];
    [foo release]; 
    foo = bar;
  }
which harmlessly increments and decrements for self-assignment.


that 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)


That would also work, autorelease is generally considered slow though.


Ah, trickier than I thought. I posted an EDIT to the blog post.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: