我可以在不创建临时数组的情况下移动NSMutableArray中的对象吗?

wil*_*lc2 7 arrays cocoa shift nsmutablearray

我以为我有它,

void shiftArray(NSMutableArray *mutableArray, NSUInteger shift)
{
    for (NSUInteger i = 0; i < [mutableArray count]; i++) {
        NSUInteger newIndex = (i + shift) % [mutableArray count];
        [mutableArray exchangeObjectAtIndex:i withObjectAtIndex:newIndex];
    }
}
Run Code Online (Sandbox Code Playgroud)

当我换一个时,它将0,1,2,3,4变成0,2,3,4,1.

预期结果是4,0,1,2,3

我觉得我错过了一些明显的东西......

更新:感谢Matthieu,这就是我现在的功能.

void shiftArrayRight(NSMutableArray *mutableArray, NSUInteger shift) {
    for (NSUInteger i = shift; i > 0; i--) {
        NSObject *obj = [mutableArray lastObject];
        [mutableArray insertObject:obj atIndex:0];
        [mutableArray removeLastObject];
    }
}
Run Code Online (Sandbox Code Playgroud)

我不知道你可以制作一个通用的NSObject并在其中加入一些子类.它只是指针所以我猜它没关系,对吧?

很难打破将这些物体视为袋子的习惯,而不是指向袋子的指针.

Mat*_*ier 13

尝试类似的东西

for (NSUInteger i = shift; i > 0; i--) {
   NSObject* obj = [mutableArray lastObject];
   [mutableArray insertObject:obj atIndex:0];
   [mutableArray removeLastObject];
}
Run Code Online (Sandbox Code Playgroud)

CAVEAT - 我没有测试过那段代码,但这应该可以帮助你解决问题.