问题描述
我想我了吧,
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];
}
}
果然0,1,2,3,4为0,2,3,4,1时,我被一个班次。
which turns 0,1,2,3,4 into 0,2,3,4,1 when I shift by one.
预期的结果是4,0,1,2,3
The expected result is 4,0,1,2,3
我觉得我缺少明显的东西...
I feel like I'm missing something obvious...
更新:感谢马修,这就是我的函数看起来像现在
Update: Thanks Matthieu, this is what my function looks like now.
void shiftArrayRight(NSMutableArray *mutableArray, NSUInteger shift) {
for (NSUInteger i = shift; i > 0; i--) {
NSObject *obj = [mutableArray lastObject];
[mutableArray insertObject:obj atIndex:0];
[mutableArray removeLastObject];
}
}
我不知道你可以做一个普通的NSObject的,并把一些子类在里面。这一切都只是指针,所以我想这是好的,对吧?
I didn't know you could make a generic NSObject and put some subclass in it. It's all just pointers so I guess it's OK, right?
这是很难打破这些对象的思维习惯的东西的袋而非指针即可收入囊中。
It's hard to break the habit of thinking of these objects as bags of stuff rather than pointers to the bag.
推荐答案
试着这么做
for (NSUInteger i = shift; i > 0; i--) {
NSObject* obj = [mutableArray lastObject];
[mutableArray insertObject:obj atIndex:0];
[mutableArray removeLastObject];
}
警告 - 我没有测试过了code,但应该可以帮助你解决问题。
CAVEAT -- I haven't tested that code, but that should help you solve the problem.
这篇关于我可以移动的NSMutableArray里的对象,而无需创建一个临时数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!