not implemented delegate method leads to crash

2019-03-25 04:31发布

问题:

I created a protocol and assigned it to a delegate object

@protocol AppBrainDelegate <NSObject>
@optional
- (void)didLocateUser;
- (void)didFinishLoadingDataWithData:(NSDictionary *)fetchedData;
@end

@interface Brain : NSObject
@property (strong, nonatomic) id <AppBrainDelegate> delegate;

I thought the meaning of this @optional in the protocol declaration means, that controllers don't have to listen to the delegate method if they don't want to.

Here's the crash log if do not implement the first of the delegate methods in the controller. If I do, I don't crash. Seems like I did not understand the concept of declaring delegate methods as optional. Can you explain to me where my mistake is?

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[EventViewController didLocateUser]: unrecognized selector sent to instance 0x1fb300'

回答1:

The @optional simply suppresses a compiler warning if the method is not implemented in a class that conforms to the protocol. Before calling the delegate method, you still need to check that the delegate implements it:

if ([delegate respondsToSelector:@selector(didLocateUser)]) {
    [delegate didLocateUser];
}

Incidentally, you have created your delegate property using strong semantics. Unless you have a particularly good reason to use strong, delegates should be weak, since your Brain class doesn't own its delegate (if you think about the object graph).