I had a problem with ARC and blocks but have solved the problem. Unfortunately I don’t what exactly is going on and would like to learn more about the situation I had.
Originally, I had code that did this
for(__block id<Foo> object in objects) {
foo download:someParm
success:^{
object.state = StateNewState;
}
];
}
This caused an imbalance in retains. A crash occurs when an object is accessed and is said to be already deallocated. I wrote a class that implemented and used the “copy” attribute to create a successBlock property which saved the block passed into the success parameter of the download function. I replaced the code with this with the following
for(id<Foo> object in objects) {
foo download:someParm
success:^(id<Foo> successObject){
successObject.state = StateNewState;
}
];
}
No more deallocated object errors but I have yet to run instruments to check if I’m not leaking. Some how using __block is causing the object to be released too many times, and I can’t figure out why. I’ll continue my research as to the cause of this issue but I thought it’d be an interesting problem for the rest of you guys to think about.
I suppose it may be worth noting that the objects array was an autoreleased array that was created in the lines proceeding the code I wrote down earlier in this post. Don’t think it’d matter but I thought I’d just through that out there. The code I put in this post isn’t the exact code, because I’m using this for work and there’s a bunch of fluff in there. But there’s no other objects being created in the for loop.
When the app crashes, it runs download and then later runs the callback, I’m using ASIHttp by the way. When I attempt to download again it runs and the callback is not called, since object has been deallocated and the delegate is nil’ed. After this when object is accessed by a dictionary that contains a pointer to object we crash.
The Blocks Programming Topics says:
Thus, if you don’t use
__block, I think you’ll find your variables are being retained for you. E.g., this seems to work for me:I found that the presence or absence of
__blockdidn’t have a material impact when myblockTestInvocationinvoked the passed block synchronously, but when I set it up to invoke the block asynchronously (after my array and objects would have otherwise been released), the absence of the__blockensured that the object was retained, thereby preventing the dreaded "message sent to deallocated instance" (and there were no leaks, either). But with__block, the object is not retained, and thus could be deallocated by the time the block of code tries to reference it.