Objective-C 中不相关对象的语义问题
我有一个 UIViewController
子类,它实现了一条消息以使用自定义模型初始化控制器:
- (id)initWithUser:(FacebookFriend *)user;
当我使用它来初始化我的控制器时:
ProfileViewController *profileViewController = [[ProfileViewController alloc] initWithUser:friend];
编译器抱怨向 NSUserDefaults
发送消息' 同名消息:
- (id)initWithUser:(NSString *)username;
warning: incompatible Objective-C types 'struct FacebookFriend *', expected 'struct NSString *' when passing argument 1 of 'initWithUser:' from distinct Objective-C type
我不太明白为什么它通知我这一点,因为我不认为 UIViewController 继承自任何地方的 NSUserDefaults 。有没有办法禁用这个错误?这会导致问题吗?我应该重命名我的类的初始值设定项以避免混淆吗?
I have a UIViewController
subclass that implements a message to init the controller with a custom model:
- (id)initWithUser:(FacebookFriend *)user;
When I use this to init my controller:
ProfileViewController *profileViewController = [[ProfileViewController alloc] initWithUser:friend];
The compiler complains about sending a message to NSUserDefaults
' message of the same name:
- (id)initWithUser:(NSString *)username;
warning: incompatible Objective-C types 'struct FacebookFriend *', expected 'struct NSString *' when passing argument 1 of 'initWithUser:' from distinct Objective-C type
I don't quite understand why it's notifying me of this as I don't think UIViewController
inherits from NSUserDefaults
anywhere. Is there a way to disable this error? Could this cause a problem? Should I just rename my class' initializer to avoid confusion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是你有一个不明确的选择器。因为
alloc
返回通用(对于 Objective C)类型id
,所以对initWithUser:
的调用变得不明确,因此它与NSUserDefaults
方法initWithUser:
。编译器认为你正在尝试使用那个。您可以通过强制转换来消除歧义:
The problem is you have an ambiguous selector. Because
alloc
returns the generic (for Objective C) typeid
, the call toinitWithUser:
has become ambiguous, and so it gets confused with theNSUserDefaults
methodinitWithUser:
. The compiler thinks you're trying to use that one.You can remove the ambiguity by casting:
您是否尝试过直接转换
-alloc
的结果?像这样的东西:Have you tried directly casting the result of
-alloc
? Something like this: