tags:

views:

29

answers:

2

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?

+2  A: 

Since -objectAtIndex: returns an id, the compiler will not be able to know what -state should return. If you did not import the header that declares state first, or if the property state has ambiguous declaration (e.g. another class has declared @property(retain) id state before 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, -4 will be implicitly viewed as 0xFFFFFFFC, thus the > 0 condition passes.

But for code 1, you have specified that temp is an int, so even if the return value of the call is 0xFFFFFFFC, 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.

Foo* obj = [[myArray objectAtIndex:iIndex] objectAtIndex:jIndex];
if (obj.state > 0) {
 ...
KennyTM
A: 

I I understand it right, and the two if's are NOT in the same method, then the second one prints an unassigned variable. the fix should go like this:

if ((temp = [[[myArray objectAtIndex:iIndex] objectAtIndex:jIndex] state]) > 0)
{
    NSLog(@"TEST: %d",temp);
}
Max Seelemann