Objective-C 中不相关对象的语义问题

发布于 2024-11-30 11:24:42 字数 698 浏览 2 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

唯憾梦倾城 2024-12-07 11:24:42

问题是你有一个不明确的选择器。因为 alloc 返回通用(对于 Objective C)类型 id,所以对 initWithUser: 的调用变得不明确,因此它与NSUserDefaults 方法 initWithUser:。编译器认为你正在尝试使用那个。

您可以通过强制转换来消除歧义:

ProfileViewController *profileViewController = [(ProfileViewController*)[ProfileViewController alloc] initWithUser:friend];

The problem is you have an ambiguous selector. Because alloc returns the generic (for Objective C) type id, the call to initWithUser: has become ambiguous, and so it gets confused with the NSUserDefaults method initWithUser:. The compiler thinks you're trying to use that one.

You can remove the ambiguity by casting:

ProfileViewController *profileViewController = [(ProfileViewController*)[ProfileViewController alloc] initWithUser:friend];
别再吹冷风 2024-12-07 11:24:42

您是否尝试过直接转换 -alloc 的结果?像这样的东西:

ProfileViewController *profileViewController = [(ProfileViewController *)[ProfileViewController alloc] initWithUser:friend];

Have you tried directly casting the result of -alloc? Something like this:

ProfileViewController *profileViewController = [(ProfileViewController *)[ProfileViewController alloc] initWithUser:friend];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文