ios 为什么我在objective-c中得到一个整数到指针转换错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9961626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why am I getting an integer to pointer conversion error in objective-c?
提问by Justin Copeland
I am looping through an NSString object called previouslyDefinedNSString
and verifying if the integer representing the ASCII value of a letter is in an NSMutableSet called mySetOfLettersASCIIValues
, which I had previously populated with NSIntegers:
我正在循环调用 NSString 对象previouslyDefinedNSString
并验证表示字母 ASCII 值的整数是否在名为 的 NSMutableSet 中mySetOfLettersASCIIValues
,我之前用 NSIntegers 填充了该对象:
NSInteger ASCIIValueOfLetter;
for (int i; i < [previouslyDefinedNSString length]; i++) {
ASCIIValueOfLetter = [previouslyDefinedNSString characterAtIndex:i];
// if character ASCII value is in set, perform some more actions...
if ([mySetOfLettersASCIIValues member: ASCIIValueOfLetter])
However, I am getting this error within the condition of the IF statement.
但是,我在 IF 语句的条件下收到此错误。
Incompatible integer to pointer conversion sending 'NSInteger' (aka 'int') to parameter of type 'id';
Implicit conversion of 'NSInteger' (aka 'int') to 'id' is disallowed with ARC
What do these errors mean? How am I converting to an object type (which id represents, right?)? Isn't NSInteger an object?
这些错误是什么意思?我如何转换为对象类型(哪个 id 代表,对吧?)?NSInteger 不是一个对象吗?
回答by Maurício Linhares
You want to make it an NSNumber, as in:
你想让它成为一个 NSNumber,如:
NSInteger ASCIIValueOfLetter;
for (int i; i < [previouslyDefinedNSString length]; i++) {
ASCIIValueOfLetter = [previouslyDefinedNSString characterAtIndex:i];
// if character ASCII value is in set, perform some more actions...
if ([mySetOfLettersASCIIValues member: [NSNumber numberWithInteger: ASCIIValueOfLetter]])
Now you're going to have the result you're looking for.
现在,您将获得想要的结果。
回答by Itai Ferber
These errors mean that member:
expects an object. id
is a pointer to an Objective-C object, and instead of an object, you're passing in a primitive type, or scalar (despite its NS-
prefix, NSInteger
is not an object - just a typedef
to a primitive value, and in your case, an int
). What you need to do is wrap that scalar value in an object, and specifically, NSNumber
, which is a class specifically designed to handle this.
这些错误意味着member:
需要一个对象。id
是指向 Objective-C 对象的指针,而不是对象,您传入的是原始类型或标量(尽管有NS-
前缀,但它NSInteger
不是对象 - 只是typedef
原始值的 a,在您的情况下,是int
)。您需要做的是将该标量值包装在一个对象中,特别NSNumber
是 ,这是一个专门设计用于处理此问题的类。
Instead of calling member:
with ASCIIValueOfLetter
, you need to call it with the wrapped value, [NSNumber numberWithInteger:ASCIIValueOfLetter]
, as Maurício mentioned.
而不是调用的member:
使用ASCIIValueOfLetter
,你需要包装的价值来调用它,[NSNumber numberWithInteger:ASCIIValueOfLetter]
如毛里西奥提及。