I am a new to objective-c, and I know the basic memory management rules like when to retain
release
autorelease
. But I don't know when should I wrap my code into autorelease pool and why?
As with other performance optimizations, you should generally only add additional autorelease pools to your code if you notice high memory usage and profiling (using Instruments, for example) leads you to additional autorelease pools as a solution.
That said, you can wrap code that creates a large number of temporary objects in a tight loop in an autorelease pool. The default autorelease pool is drained at the end of a run loop cycle. So, if you're creating lots of temporary objects in each iteration of a for loop in your code, the default autorelease pool won't be drained until after your entire loop has run, meaning all the temporary objects you create can add up to a high temporary memory usage (sometimes called the "high water mark"). You can wrap each iteration of the loop in an @autoreleasepool
to cause unneeded, autoreleased, temporary objects created in that loop iteration to be released sooner.