我可以在NSMutableArray中移动对象而不创建临时数组? [英] Can I shift the objects in a NSMutableArray without creating a temporary array?

查看:191
本文介绍了我可以在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];
    }
}

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

The expected result is 4,0,1,2,3

我觉得我缺少明显的东西...

I feel like I'm missing something obvious...

更新:感谢Matthieu

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];
}



CAVEAT - 我没有测试过这个代码,解决问题。

CAVEAT -- I haven't tested that code, but that should help you solve the problem.

这篇关于我可以在NSMutableArray中移动对象而不创建临时数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆