Emil
Emil

Reputation: 7256

Why doesen't the number 2 work in this for-loop?

I have a function that runs trough each element in an array. It's hard to explain, so I'll just paste in the code here:

NSLog(@"%@", arraySub);

for (NSNumber *favoriteThing in arrayFav){  

    int favoriteLoop = [favoriteThing intValue] + favCount;
    NSLog(@"%d", favoriteLoop);

    id arrayFavObject = [array objectAtIndex:favoriteLoop];
    [arrayFavObject retain];
    [array removeObjectAtIndex:favoriteLoop];
    [array insertObject:arrayFavObject atIndex:0];
    [arrayFavObject release];

    id arraySubFavObject = [arraySub objectAtIndex:favoriteLoop];
    [arraySubFavObject retain];
    [arraySub removeObjectAtIndex:favoriteLoop];
    [arraySub insertObject:arraySubFavObject atIndex:0];
    [arraySubFavObject release];

    id arrayLengthFavObject = [arrayLength objectAtIndex:favoriteLoop];
    [arrayLengthFavObject retain];
    [arrayLength removeObjectAtIndex:favoriteLoop];
    [arrayLength insertObject:arrayLengthFavObject atIndex:0];
    [arrayLengthFavObject release];

}

NSLog(@"%@", arraySub);

The array arrayFav contains these numbers: 3, 8, 2, 10, 40. Array array contains 92 strings with a name. Array arraySub contains numbers 0 to 91, representing a filename with a title from the array array. Array arrayLength contains 92 strings representing the size of each file from array arraySub.

Now, the first NSLog shows, as expected, the numbers 0 to 91. The NSLog-s in the loop shows the numbers 3, 8, 2, 10, 40, also as expected.

But here's the odd part: the last NSLog shows these numbers: 40, 10, 0, 8, 3, 1, 2, 4, 5, 6, 7, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91

that is 40, 10, 0, 8, 3, and so on.

It was not supposed to be a zero in there, it was supposed to be a 2..

Do you have any idea at why this is happening or a way to fix it? Thank you.

EDIT: Code has changed. arrayFav now contains numbers.

Upvotes: 1

Views: 100

Answers (2)

Emil
Emil

Reputation: 7256

I fixed this by removing the for-loop and just search for the correct location in the arraySub.

// If the object is not really the object we want, get what we want
if (favoriteLoop != [[[arraySub objectAtIndex:favoriteLoop] description] intValue]){
    favoriteLoop = [arraySub indexOfObject:[NSString stringWithFormat:@"%d", favoriteLoop]];
}         

Upvotes: 0

Alex Reynolds
Alex Reynolds

Reputation: 96937

The -intValue method returns 0 if there is something funky about the beginning of the string being converted.

Instead of using NSString to store integers, try using NSNumber to enforce storing numbers in your array, or debug what is being sent the -intValue message.

Upvotes: 2

Related Questions