Monday, March 7, 2011

Remembering to use NSAutoreleasePool after calling performSelector

There's nothing worse than working really hard on an iPhone game or app, only to be plagued by poor performance, memory leaks and out-of-control allocations. One of the most important things I routinely forget to do is to auto-release every time i use a perform selector. For example, if I want to play an announcement in 2 seconds, i might say:


[self performSelector:@selector(playAnnouncement) withObject:nil afterDelay:2];

and then it's really important to add the NSAutoreleasePool to the selector method, like so...

-(void)playAnnouncement{
     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
     ... code to play the announcement ...
     [pool release];
}


And there's that.

2 comments:

  1. really? Even inside the Main Thread? Whoa, that's weird! When we call perform selector, actually what happens? You know?

    ReplyDelete
  2. i believe it's necessary to use NSAutoReleasePool for performSelector calls because the invocation will happen in a new thread...
    however, i do NOT believe you need to use NSAutoReleasePool when calling performSelectorOnMainThread, since the invocation happens in the same thread.
    i think that's right, does that make sense?

    ReplyDelete