在具有可变参数的方法中投射警告

发布于 2024-08-27 04:27:12 字数 586 浏览 7 评论 0原文

抱歉,如果问题不正确,我对 Objective-C 还很陌生。
我明白为什么这段代码会抛出警告:“警告:传递'initWithObjectsAndKeys:'的参数1使指针从整数没有”

NSDictionary *dictNames =
[[NSDictionary alloc] initWithObjectsAndKeys:
     3, @"",
     4, @"",
     5, @"",nil];

NSDictionary的键和值必须是NSObject而不是基本类型,例如整数3、4 和 5。(如有必要请纠正我)。
但我不明白为什么这个警告会随着第一个键的唯一“正确输入”而消失。

NSDictionary *dictNames =
    [[NSDictionary alloc] initWithObjectsAndKeys:
     [NSNumber numberWithInteger:3], @"",
     4, @"",
     5, @"",nil];

这是因为 NSDictionary 假定了其他 Key 的类型?这种初始化方式正确吗?

Sorry if the question isn't correct, I'm very new in Objective-C.
I understand why this code throw the Warning: "warning: passing argument 1 of 'initWithObjectsAndKeys:' makes pointer from integer without"

NSDictionary *dictNames =
[[NSDictionary alloc] initWithObjectsAndKeys:
     3, @"",
     4, @"",
     5, @"",nil];

Keys and Values of a NSDictionary must be NSObject and not fundamental types, like the integers 3, 4 and 5. (Correct me if necessary).
But I don't understand why this warning dissapears with the only "correct typing" of the first Key.

NSDictionary *dictNames =
    [[NSDictionary alloc] initWithObjectsAndKeys:
     [NSNumber numberWithInteger:3], @"",
     4, @"",
     5, @"",nil];

It's because NSDictionary assumes the type of the other Keys? Is correct this manner of initialization?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

囚你心 2024-09-03 04:27:12

您提到的方法的原型是

-(id)initWithObjectsAndKeys:(id)firstObject, ...;

因此第一个参数必须是 ObjC 对象。但其余的则由可变参数传递。在 C 中,任何原语都可以作为 vararg 参数传递(想想 printf)。因此编译器不会发出任何警告。

虽然编译器无法检查 vararg 参数的类型,但这并不意味着将非 id 传递到方法中是有效的。

The prototype of the method you mentioned is

-(id)initWithObjectsAndKeys:(id)firstObject, ...;

Thus the first parameter must be an ObjC object. But the rest are passed by varargs. In C, any primitives can be passed as vararg arguments (think printf). Hence the compiler won't issue any warnings.

While the compiler is incapable of chekcing the types of the vararg arguments, it doesn't mean passing non-id into the method is valid.

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