Luck Yong
Luck Yong

Reputation: 111

Comparison between pointer and integer error

for(NSInteger i = 0; i<[_tempPostalCodeList count]; i++){
            ***if(individualInfo.postalCode == [[_tempPostalCodeList objectAtIndex:i] postalCode])***{
                myAnnotation.title = [NSString stringWithFormat:@"%i Records!", [[_postalCount objectAtIndex:i] intValue]];
            }
    }

I Do not know what is wrong with this piece of code. That line has a error. This works for Java but not for objective c. =( Someone plz help

Upvotes: 1

Views: 569

Answers (1)

Adam Rosenfield
Adam Rosenfield

Reputation: 400692

Despite the lack of a lot of information in the question, my psychic powers tell me that the problem is that the message -objectAtIndex: of the NSArray class returns a generic object of type id. So, the expression [[_tempPostalCodeList objectAtIndex:i] postalCode] is sending the postalCode message to an object of type id. Since the compiler doesn't know the underlying type of the actual object, it can't deduce the return type of the postalCode message, so it assumes that it also returns id.

id is a pointer type, and since postalCode is an integral type, the compiler thinks you're trying to compare a pointer with an integer when it evaluates the == operator, hence the warning. The way to fix this is to either insert a cast, or introduce a temporary variable:

// Option #1: Use a cast
if(individualInfo.postalCode ==
    [(MyClass*)[_tempPostalCodeList objectAtIndex:i] postalCode]) {
    ...
}

// Option #2: Use a temporary variable
MyClass *obj = [_tempPostalCodeList objectAtIndex:i];
if(individualInfo.postalCode == obj.postalCode) {
    ...
}

The reason that you can use a temporary variable without a cast is because the id type (returned by -objectAtIndex:) can be implicitly cast to any Objective-C class type by simple assignment (similar to how in C (but not C++), the void* type can be implicitly cast to any pointer type).

Upvotes: 4

Related Questions