Addev
Addev

Reputation: 32243

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

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

Crashed: com.apple.main-thread

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?

Upvotes: 0

Views: 183

Answers (1)

Antony Raphel
Antony Raphel

Reputation: 2078

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"). A weak delegate reference is standard practice.

Upvotes: 1

Related Questions