简体   繁体   English

在目标C中使用弱引用时,BAD_ACCESS

[英]BAD_ACCESS when using a weak reference in Objective C

I'm having a problem within my app. 我的应用程序出现问题。 In a class I declare a weak delegate property: 在一个类中,我声明了一个弱的委托属性:

@interface FeedManager : NSObject

@property (nonatomic, assign) id<FeedDelegate> delegate;

...
@end

where the FeedDelegate defines the method -getViewController FeedDelegate在其中定义方法-getViewController

Within the implementation, in a given callback I was trying to call to the delegate: 在实现中,在给定的回调中,我试图调用委托:

@implementation FeedManager
   ...
   -(void) presentUpdates {
       if([self.delegate respondsToSelector:@selector(getViewController)]) {
           //Do stuff
       }
   }
   ...
}

I saw this was causing runtime crashes in the if line with 我看到这在if行中导致运行时崩溃

Crashed: com.apple.main-thread 崩溃:com.apple.main-thread

EXC_BAD_ACCESS KERN_INVALID_ADDRESS EXC_BAD_ACCESS KERN_INVALID_ADDRESS

So I thought it was trying to access to the deallocated delegate so I added a null check in order to avoid it 所以我认为这是在尝试访问已释放的委托,因此我添加了一个空检查以避免它

if(self.delegate &&[self.delegate respondsToSelector:@selector(getViewController)])

But it is still crashing with the same error. 但是它仍然崩溃并出现相同的错误。 How can I avoid that runtime error? 如何避免该运行时错误?

Change your delegate property 更改您的代表财产

@property (nonatomic, assign) id<FeedDelegate> delegate;

into

@property (nonatomic, weak) id<FeedDelegate> delegate;

This specifies that objects of the current class have a delegate that can be of any type. 这指定当前类的对象具有可以是任何类型的委托。 The weak specifier is common for delegate objects as it means the object with the delegate does not increment the delegate's reference count (in ARC-speak "keep a strong reference of it"). 弱指定符对于委托对象是常见的,因为这意味着具有委托的对象不会增加委托的引用计数(在ARC中,请说“保持对其的强烈引用”)。 A weak delegate reference is standard practice. 较弱的委托人引用是标准做法。

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

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