Search code examples
iosobjective-cintnsarraytype-conversion

How can an int be converted into an id?


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?

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

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

Solution

  • componentsSeparatedByString: docs says:

    Return value

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

    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

    [string intValue];
    [string integerValue];
    

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

    int object1 = [fileContents[0] intValue];
    

    Or even better include typecasting for better code readability

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