简体   繁体   English

启动成功阻止时,__ block弱正在崩溃

[英]__block weak is crashing when success block is initiated

I am having a hard time understanding this: 我很难理解这一点:

__block __weak MyCell *weakSelf = self;
[NetworkManager profileImageForUser:id success ^(UIImage *image, NSString *userId){
       weakSelf.leftImageView.image = image;
}];

The issue is that when MyCell is deallocated and then the success block is initiated, then it crashes saying unrecognized selector sent to instance. 问题是,当释放MyCell并启动成功块时,它崩溃,表示无法识别的选择器已发送到实例。 How do I deal with this? 我该如何处理?

The reason this crash is happening is that weakSelf is not being retained by the block, which is probably executed asynchronously after the deallocation of the object. 发生崩溃的原因是该块未保留weakSelf,这可能是在对象解除分配之后异步执行的。

Why are you using __block here? 为什么在这里使用__block? This is the cause of your problem. 这是导致您出现问题的原因。

__block is only necessary when you are going to MODIFY the object in question from inside the block. 仅当要从块内部修改有问题的对象时,才需要__block。 __block also prevents the behaviour of the block retaining the object. __block还可以防止保留对象的块的行为。 Since you are not changing the VALUE of weakSelf (only it's properties), you should not use __block so that the block will retain the object and thus have it in memory when it is required, preventing this crash. 由于您没有更改weakSelf的值(仅它的属性),因此不应使用__block,这样该块将保留该对象,并在需要时将其保存在内存中,以防止发生崩溃。

How do you deal with this? 您如何处理? You could just check the value of weakSelf to make sure it's not nil before you use it (because you've effectively said that you didn't want it to be retained, but it will be set to nil if the object was released): 您可以在使用它之前检查一下weakSelf的值以确保它不是nil (因为您已经有效地表示您不希望保留它,但是如果释放了该对象,它将被设置为nil ):

__weak MyCell *weakSelf = self;
[NetworkManager profileImageForUser:id success ^(UIImage *image, NSString *userId){
       if (weakSelf)
           weakSelf.leftImageView.image = image;
}];

Or just abandon the use of weakSelf and use self (which will retain it for you until the block completes): 或者只是放弃使用weakSelf并使用self (它将在块完成之前为您保留):

[NetworkManager profileImageForUser:id success ^(UIImage *image, NSString *userId){
       self.leftImageView.image = image;
}];

Either way, don't use __block since you're not changing the object itself, just its properties. 无论哪种方式,都不要使用__block因为您不会更改对象本身,而只是更改其属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM