Justin Copeland
Justin Copeland

Reputation: 1951

Why am I getting an integer to pointer conversion error in objective-c?

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:

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.

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?

Upvotes: 8

Views: 21989

Answers (2)

Itai Ferber
Itai Ferber

Reputation: 29809

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.

Instead of calling member: with ASCIIValueOfLetter, you need to call it with the wrapped value, [NSNumber numberWithInteger:ASCIIValueOfLetter], as Maurício mentioned.

Upvotes: 11

Maur&#237;cio Linhares
Maur&#237;cio Linhares

Reputation: 40333

You want to make it an NSNumber, as in:

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.

Upvotes: 19

Related Questions