Probably the two biggest issues to watch for are 1) retain cycles, where x retains y and y retains x thus they're never freed. This usually happens with blocks. And 2) when using Core Foundation functions (Core Graphics etc), for example: CGImageCreate
, CGImageRetain
, CGImageRelease
. You still need to manually manage the memory in those cases.
A common pattern to prevent retain cycles is to create a weak reference to one of the objects that would be in the cycle. (Often self). Such as this:
__weak typeof(self) weakSelf = self;
[self useBlock:^{
typeof(weakSelf) strongSelf = weakSelf;
// do something with strongSelf
}];
Notes:
a) The reason you want to create a new strongSelf inside the block, is to ensure you're retaining the weakSelf variable for the duration of the block. Otherwise, you can have cases where weakSelf will become nil part way through the block. In some cases, you may want to add a test that strongSelf still exists immediately, and if not abort the block altogether. As weakSelf could become nil before the block starts.
__weak typeof(self) weakSelf = self;
[self useBlock:^{
typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) return;
// do something with strongSelf
}];
b) You only need to do this when self will be retaining the block (in this case via something the unknown useBlock method is doing).