你如何将int转换为id?

时间:2022-10-10 19:51:15

I have an array, and the contents of it are objects of type id, but I need to turn them into type int. Is there any way I can make the array read the data as ints, or turn the id into an int?

我有一个数组,它的内容是id类型的对象,但我需要将它们转换为int类型。有什么方法可以让数组以int的形式读取数据,或者将id转换为int?

    NSArray *array = [string componentsSeparatedByString:@"\n"];

    int foo = array[0];  /*Warning: Incompatible pointer to integer conversion initializing 'int' with an expression of type 'id' */

2 个解决方案

#1


4  

componentsSeparatedByString: docs says:

componentsSeparatedByString:docs说:

Return value

An NSArray object containing substrings from the receiver that have been divided by separator.

一个NSArray对象,包含已被分隔符划分的接收器的子串。

So your fileContents contains an array of NSStrings. fileContents[0] is then the first NSString instance in the array. And you can convert NSString to int or preferably NSInteger by calling

所以你的fileContents包含一个NSStrings数组。然后fileContents [0]是数组中的第一个NSString实例。你可以通过调用将NSString转换为int或者最好是NSInteger

[string intValue];
[string integerValue];

So your code should look like this (assuming array contains at least 1 object, don't forget to check this):

所以你的代码应该是这样的(假设数组包含至少1个对象,不要忘记检查这个):

int object1 = [fileContents[0] intValue];

Or even better include typecasting for better code readability

或者甚至更好地包括类型转换以获得更好的代码可读性

int object1 = [(NSString *)fileContents[0] intValue];

#2


2  

You should use intValue to convert to int.

您应该使用intValue转换为int。

int object1 = [fileContents[0] intValue]; 

#1


4  

componentsSeparatedByString: docs says:

componentsSeparatedByString:docs说:

Return value

An NSArray object containing substrings from the receiver that have been divided by separator.

一个NSArray对象,包含已被分隔符划分的接收器的子串。

So your fileContents contains an array of NSStrings. fileContents[0] is then the first NSString instance in the array. And you can convert NSString to int or preferably NSInteger by calling

所以你的fileContents包含一个NSStrings数组。然后fileContents [0]是数组中的第一个NSString实例。你可以通过调用将NSString转换为int或者最好是NSInteger

[string intValue];
[string integerValue];

So your code should look like this (assuming array contains at least 1 object, don't forget to check this):

所以你的代码应该是这样的(假设数组包含至少1个对象,不要忘记检查这个):

int object1 = [fileContents[0] intValue];

Or even better include typecasting for better code readability

或者甚至更好地包括类型转换以获得更好的代码可读性

int object1 = [(NSString *)fileContents[0] intValue];

#2


2  

You should use intValue to convert to int.

您应该使用intValue转换为int。

int object1 = [fileContents[0] intValue];