不兼容的整数到指针转换,将“NSInteger”(又名“int”)发送到“NSInteger *”类型的参数(又名“int *”)

问题描述 投票:0回答:4

我正在尝试使用代码从 NSDictionary 解析整数

[activeItem setData_id:[[NSString stringWithFormat:@"%@", [dict valueForKeyPath:@"data_id"]] integerValue]];

但是,这给了我这个错误:

Incompatible integer to pointer conversion sending 'NSInteger' (aka 'int') to parameter of type 'NSInteger *' (aka 'int *')

setData_id 以整数作为参数。如果我想解析为字符串,

[NSString stringWithFormat:@"%@", [dict valueForKeyPath:@"data_id"]]
可以完美工作。

我在这里所做的是将 valueForKeyPath 的结果解析为字符串,然后从中解析一个整数。

ios objective-c nsdictionary
4个回答
27
投票

你的

setData_id:
方法是如何声明的?

看起来它期望的是

NSInteger *
而不是
NSInteger
...

要么声明为:

- ( void )setData_id: ( NSInteger )value;

您可以使用您的代码。

否则,表示声明为:

- ( void )setData_id: ( NSInteger * )value;

这可能是一个错字......如果你确实需要一个整数指针,那么你可以使用(假设你知道你在范围方面做什么):

NSInteger i = [ [ NSString stringWithFormat: @"%@", [ dict valueForKeyPath: @"data_id" ] ] integerValue ];
[ activeItem setData_id: &i ];

但我认为你只是犯了一个拼写错误,添加了一个指针(

NSInteger *
),而你的意思是
NSInteger

注意:如果

setData_id
是属性,则同样适用:

@property( readwrite, assign ) NSInteger data_id;

对:

@property( readwrite, assign ) NSInteger * data_id;

我猜你写了第二个例子,而意思是第一个......


4
投票

属性定义不正确。

应该是:

@property (readwrite) NSInteger data_id;

而不是

@property (readwrite) NSInteger *data_id;

您正在尝试将整数值传递给需要指针类型的格式。

无论使用

[activeItem setData_id:[NSString stringWithFormat:@"%@", [dict valueForKeyPath:@"data_id"]]];

[activeItem setData_id:[NSString stringWithFormat:@"%d", [[dict valueForKeyPath:@"data_id"] integerValue]]];

如果您需要设置一个整数,请删除

[NSString stringWithFormat:@"%@"]
- 这将创建一个字符串。

[activeItem setData_id:[[dict valueForKeyPath:@"data_id"] integerValue]];

0
投票

在适当的情况下使用 integerValueintValue


0
投票

Xcode 15.3 已开始抛出不兼容指针类型的错误。快速修复是查看是否有 NSInteger 变量声明为的实例

NSInteger *索引;

并将其替换为

NSInteger 索引

它应该与上述修复一起使用。

© www.soinside.com 2019 - 2024. All rights reserved.