views:

101

answers:

2

Once again :)

I've got the following code:

-(void)removeFilesWithPathIndices:(NSIndexSet*)indexSet {
    NSInteger index = [indexSet firstIndex];
    while(index >= 0) {
        [self removeFileWithPathIndex:index];
        index = [indexSet indexGreaterThanIndex:index];
    }
}

Which should iterate through an NSIndexSet. However, the while loop does not stop, even though index = -1 according to

 NSLog(@"%d", index);

Anyone able to solve this mistery for me? :)

+5  A: 

indexGreatherThanIndex: returns NSNotFound when there's nothing greater than the specified index. Apple Documentation

NSNotFound is defined as NSIntegerMax, which is >= 0. Apple Documentation

Your NSLog statement is just giving you a deceptive result. Instead of:

while(index >= 0)

Use:

while(index != NSNotFound)
chrissr
+10  A: 

Don't assume NSInteger to be an int. In fact it's not. So, %d in

NSLog(@"%d", index);

is deceiving you if you compile in 64 bit mode. See NSInteger documentation.

You shouldn't have even assumed that indexGreaterThanIndex to return -1. The documentation explicitly says it returns NSNotFound. By following the documentation, you eventually find NSNotFound is NSIntegerMax, the maximal possible value in an NSInteger. When NSInteger is long and casted into an int, his becomes -1. But it's an implementation detail, and you shouldn't rely on that. That's why they defined a symbolic constant NSNotFound to start with.

You should have followed what the documentation says, and write a code like

while(index != NSNotFound) {
    [self removeFileWithPathIndex:index];
    index = [indexSet indexGreaterThanIndex:index];
}

In a sense you shouldn't have even declared

NSInteger index;

because the indices in Foundation are all NSUInteger.

Yuji
Yeah, I changed it to NSInteger after getting confused that index became -1 and I somehow thought that my problem was related to that... Anyhow, I definitely should've read the docs on this one, sorry guys x( The bad side of autocompletion :PThanks anyway :)
x3ro
Deleting my answer as you've got my point and more - `NSNotFound` is `NSIntegerMax` though, not the maximum for `NSUInteger`. This is `LONG_MAX` on 64bit which then becomes `-1` for `printf()` due to `%d`.
Georg Fritzsche
Ah, good point. Corrected the answer. Thanks for pointing it out.
Yuji