Objective-C 属性获取器抛出异常'Unrecognized selector sent to instance'



我是Objective-C的新手。我在尝试使用属性getter时遇到问题。我有一个属性来访问一个非常简单的类的实例。我的界面是这样的:

@interface AppDelegate : UIResponder <UIApplicationDelegate>
//...
@property (strong, nonatomic, readonly) MyController* myController;
@end

我的实现看起来像这样:

@implementation AppDelegate
{
}
@synthesize myController = _myController;
....
//Getter
- (MyController*)myController
{
    return _myController;
}
@end

在我的项目的其他地方,我正在尝试使用getter。它失败得很惨。

AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication];
MyController* myController = appDelegate.myController; //unrecognized selector sent to instance

作为Objective-C的新手,我确信我做错了什么。这里怎么了?

用以下内容替换实例化appDelegate的调用:

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

现在,您正在向UIApplication实例而不是AppDelegate实例发送消息。注意,+[UIApplication sharedApplication]的返回类型是UIApplication *-[UIApplication delegate]的返回类型为id<UIApplicationDelegate>(在运行时,假设所有配置都正确,则此委托对象将是AppDelegate实例。

错误消息可能会在这里给你一个提示——它可能是这样的:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIApplication myController]: unrecognized selector sent to instance

原因部分中UIApplication的存在告诉UIApplication类无法识别此选择器,而方括号前的-表示消息已发送到UIApplication的实例。如果您向类对象发送了一个无法识别的选择器,那么-将被+替换(这是用于传递方法签名的常用表示法)。

相关内容

最新更新