not implemented delegate method leads to crash

删除回忆录丶 提交于 2020-01-12 07:00:11

问题


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).



来源:https://stackoverflow.com/questions/9018764/not-implemented-delegate-method-leads-to-crash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!