未实现的委托方法导致崩溃 [英] not implemented delegate method leads to crash

查看:143
本文介绍了未实现的委托方法导致崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个协议并将其分配给委托对象

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;

我认为协议声明中这个@optional的含义意味着控制器不必如果不想,请听代理方法。

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?


* 由于未捕获的异常终止应用程序NSInvalidArgumentException原因:' - [EventViewController didLocateUser]:无法识别的选择器发送到实例0x1fb300'

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


推荐答案

@optional 只要在符合协议的类中没有实现该方法,就会禁止编译器警告。在调用委托方法之前,您仍然需要检查代理是否实现它:

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];
}

顺便提一句,你已经使用 strong创建了你的委托属性语义。除非你有一个特别好的理由使用 strong ,否则代表应该是 weak ,因为你的大脑类不会自己的它的委托(如果你考虑对象图)。

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

这篇关于未实现的委托方法导致崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆