Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap values in NSMutableArray?

This piece of codes segment fault on me, any idea why? allButtons is a NSMutableArray, it contains 3 objects, a=0, b=1, a and b are int type

 if(a != -1 && b!= -1){
    //Swap index in "allButtons"
    id tempA = [allButtons objectAtIndex:a];
    id tempB = [allButtons objectAtIndex:b];
    [allButtons replaceObjectAtIndex:a withObject:tempB]; //Seg fault here?????
    [allButtons replaceObjectAtIndex:b withObject:tempA];
    needLoad = false;
    [self setUpButtons];
 }

EDIT:

 NSMutableArray *allButtons = //fetch the array from Coredata. This work since I display the data onto the screen, plus, [allButtons count] return 3, and a=0, b=1
 f(a != -1 && b!= -1){
    //Swap index in "allButtons"
    [allButtons exchangeObjectAtIndex:a withObjectAtIndex:b];
    needLoad = false;
    [self setUpButtons];
 }
like image 651
Thang Pham Avatar asked Apr 07 '10 04:04

Thang Pham


2 Answers

The first call to replaceObjectAtIndex: will release the old object (tempA), but that shouldn't cause a seg fault. As @Zoran mentioned try logging the retainCount for tempA and verify its count.

Also for swapping elements in an array, you should use exchangeObjectAtIndex:withObjectAtIndex instead of replaceObjectAtIndex:withObject. It's supported from iPhone 2.0.

like image 154
Anurag Avatar answered Oct 01 '22 15:10

Anurag


Just because you have said

NSMutableArray *allbuttons = // something

doesn't mean that it is definitely an NSMutableArray, it just means that the compiler thinks that it will be a NSMutableArray.

If it's from CoreData, it's probably just an NSArray so the method calls you are trying won't work - you'll get unrecongnised selector or something like that.

You will have to convert it to a mutable array first

NSArray *coreData = // core data call

// Create a mutable copy
// NB This means that you are now working on a copy, not the original :)
NSMutableArray *allButtons = [coreData mutableCopy];
like image 21
deanWombourne Avatar answered Oct 01 '22 15:10

deanWombourne