我发现了一些属于此警告的类似问题,但没有回答或没有真正准确地提出。
我的 AppDelegate 有一个名为 AppModel* iVarModel 的实例变量。 App Delegate 有一个已声明的属性,同时甚至还有一个单独的 getter,例如:
AppDelegate.h
AppModel* iVarModel;
@property (nonatomic, retain) AppModel* iVarModel;
- (AppModel*) getAppModel;
AppDelegate.m
@synthesize iVarModel;
- (AppModel*) getAppModel {
return iVarModel;
}
在不同的类(class) 我喜欢通过单例应用程序对象访问它:
FarFarAwayClass.h
import "AppDelegate.h"
...
FarFarAwayClass.m
//get a pointer to the application object
UIApplication* thisApp = [UIApplication sharedApplication];
// get a pointer to the application's delegate
id<UIApplicationDelegate> theDelegateObject = [thisApp delegate];
// >(1)< access AppModel's property iVarModel
AppModel* iVarModel_byProp = [theDelegateObject iVarModel];
// >(2)< access AppModel's iVarModel via getter
AppModel* iVarModel_byGet = [theDelegateObject getAppModel];
独立于我如何尝试访问它 >(1)< 或 >(2)< 它有效,但我确实收到此警告:
Instance method '-iVarModel' not found (return type defaults to 'id')
Instance method '-getAppModel' not found (return type defaults to 'id')
为什么编译器认为这些方法不存在,即使他可以正确使用它们?
顺便说一下,如果我跳过 getter 或声明的属性,我总是会收到此警告。
最佳答案
编译器警告你是因为你告诉编译器这个局部变量“theDelegateObject”的类型是“id”。换句话说,你说它是“实现 UIApplicationDelegate 协议(protocol)的一些 NSObject”。您没有说它是您的特定 AppDelegate 类的实例。
如果你这样做,编译器会知道你在做什么:
MyAppDelegate* theDelegateObject = (MyAppDelegate*) [thisApp delegate];
这为编译器提供了类型信息,它需要知道该对象应该响应您编写的自己的方法。
至于为什么这在运行时能正常工作,记住消息传递是动态的,编译器不需要在编译时绑定(bind)到这个方法。它只是尽职尽责地编写您要求的方法调用。在运行时,这是可行的,因为应用程序的委托(delegate)原来是 AppDelegate 类的实际实例。
希望这是有道理的?
关于objective-c - 警告 "Instance method ' - 未找到方法名称(返回类型默认为 'id')”,但它存在并且工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8057916/