i have the following two pieces of code which i think should be identical
int temp = [[[myArray objectAtIndex:iIndex] objectAtIndex:jIndex] state];
if (temp > 0)
{
NSLog(@"TEST: %d",temp);
}
if ([[[myArray objectAtIndex:iIndex] objectAtIndex:jIndex] state] > 0)
{
NSLog(@"TEST: %d",temp);
}
state is just an int in the objects in the array with accessor like:
@property (assign)int state;
but when state is negative, the first version works (no output), but the second version outputs (for example) “TEST: -4” (?!)
is there any obvious reason why they might be different?
Since
-objectAtIndex:returns anid, the compiler will not be able to know what-stateshould return. If you did not import the header that declaresstatefirst, or if the propertystatehas ambiguous declaration (e.g. another class has declared@property(retain) id statebefore your class is imported), then the compiler may infer a wrong type for-state.If it infers
id, for instance, as all pointers are nonnegative,-4will be implicitly viewed as0xFFFFFFFC, thus the > 0 condition passes.But for code 1, you have specified that
tempis anint, so even if the return value of the call is0xFFFFFFFC, it will be cast back to a signed value (-4), hence the condition fails.The safest approach is to specify the type of
-objectAtIndex:, i.e.