我是 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>
(在运行时,假设所有配置都正确,这个委托(delegate)对象将是一个 AppDelegate
实例。
错误消息可能会在这里给你一个提示——它可能是这样的:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIApplication myController]: unrecognized selector sent to instance
UIApplication
的存在在原因部分告诉您 UIApplication
类不识别这个选择器,而 -
方括号之前表示消息已发送到 UIApplication
的实例.如果您向类对象发送了无法识别的选择器,则 -
将被替换为 +
(这是通信方法签名的常用符号)。
关于ios - Objective-C 属性 getter 抛出异常 'Unrecognized selector sent to instance',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20392559/