如何在NSMutableArray中交换值?

Tha*_*ham 9 iphone objective-c nsmutablearray

这段代码对我有疑问,有什么想法吗?allButtons是a NSMutableArray,它包含3个对象a=0, b=1,a和b是int类型

 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];
 }
Run Code Online (Sandbox Code Playgroud)

编辑:

 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];
 }
Run Code Online (Sandbox Code Playgroud)

Anu*_*rag 22

第一次调用replaceObjectAtIndex:将释放旧对象(tempA),但这不应该导致seg错误.正如@Zoran所提到的,尝试记录retainCounttempA并验证其计数.

另外,对于交换数组中的元素,您应该使用exchangeObjectAtIndex:withObjectAtIndex而不是replaceObjectAtIndex:withObject.它受iPhone 2.0的支持.


dea*_*rne 11

只因为你说过

NSMutableArray *allbuttons = // something
Run Code Online (Sandbox Code Playgroud)

并不意味着它肯定是一个NSMutableArray,它只是意味着编译器认为它将是一个NSMutableArray.

如果它来自CoreData,它可能只是一个NSArray所以你尝试的方法调用将无法工作 - 你会得到未经识别的选择器或类似的东西.

您必须先将其转换为可变数组

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];
Run Code Online (Sandbox Code Playgroud)