Using blocks and ARC is causing a “message sent to

2019-06-14 16:30发布

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.

2条回答
\"骚年 ilove
2楼-- · 2019-06-14 17:07

Two things:

1) Something doesn't add up about what you've described. You say you're putting these objects in an autoreleased array, which is presumably temporary storage for the purpose of running the loop. Then your block callbacks set some state on those objects, which would be pointless unless something else is also retaining them. So your problem lies in the something else--whatever created those objects should be retaining them while it needs them--presumably long enough to observe the state change. If it were, you wouldn't be getting EXC_BAD_ACCESS errors.

2) You don't need the __block qualifier in your loop. It's basically telling the compiler that your block may assign a new object to that reference, so it needs to dereference the variable. But your block doesn't do that. You're just sending a message to the object. If you don't use the __block qualifier, your block will take a const copy of the value--that value is a pointer to your object. Then when you do object.state = StateNewState, you're sending a setState:newState message to the object at that pointer. So this should work fine:

for(id<Foo> object in objects) {
    foo download:someParm
         success:^{
            object.state = StateNewState; 
         }
    ];
}
查看更多
\"骚年 ilove
3楼-- · 2019-06-14 17:12

The Blocks Programming Topics says:

Use of instance variables within the block will cause the object itself to be retained. If you wish to override this behavior for a particular object variable, you can mark it with the __block storage type modifier.

If you are using ARC, object variables are retained and released automatically as the block is copied and later released.

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:

NSMutableArray *array = [[NSMutableArray alloc] init];

// add two custom objects to that array

[array addObject:[[MyObject alloc] initWithText:@"One" number:1]];
[array addObject:[[MyObject alloc] initWithText:@"Two" number:2]];
[array addObject:[[MyObject alloc] initWithText:@"Three" number:3]];

// now replace the text field in each of the three objects with the word "Done"

for (MyObject *object in array)
{
    [self blockTestInvocation:^{
        NSLog(@"%s %@", __FUNCTION__, [NSDate date]);

        object.text = @"Done";
    }];
}

I found that the presence or absence of __block didn't have a material impact when my blockTestInvocation invoked 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 __block ensured 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.

查看更多
登录 后发表回答