如何将NSArray分成两个相等的部分? [英] How to split an NSArray into two equal pieces?

查看:76
本文介绍了如何将NSArray分成两个相等的部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSArray,我想将其分成两个相等的部分(如果奇数"加到后面的新数组中)-可以这么说.

I have an NSArray, and I want to split it into two equal pieces (if odd "count" then add to the latter new array) - I want to split it "down the middle" so to speak.

以下代码完全符合我的要求,但是有更好的方法吗?:

The following code does exactly what I want, but is there a better way?:

// NOTE: `NSArray testableArray` is an NSArray of objects from a class defined elsewhere;
NSMutableArray *leftArray = [[NSMutableArray alloc] init];  
NSMutableArray *rightArray = [[NSMutableArray alloc] init];

for (int i=0; i < [testableArray count]; i=i+1) {
if (i < [testableArray count]/2) {
        [leftArray addObject:[testableArray objectAtIndex:i]];
    }
    else {
        [rightArray addObject:[testableArray objectAtIndex:i]];
    }
}

一旦创建了leftArray和rightArray,我就不会更改它们,因此它们不必是可变的".我认为可能有一种方法可以使用ObjectsAtIndexes方法或某些快速枚举方法来完成上述代码?但我无法使以下代码正常工作(或其他变体):

Once leftArray and rightArray are made, I will not change them, so they do not need to be "mutable". I think there may be a way to accomplish the above code with the ObjectsAtIndexes method or some fast enumeration method?, but I cannot get the following code to work (or other variations):

NSArray *leftArray = [[NSArray alloc] initWithObjects:[testableArray objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(????, ????)]]];
NSArray *rightArray = [[NSArray alloc] initWithObjects:[testableArray objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(????, ????)]]];

有人知道我是朝着正确的方向前进还是指向正确的方向?

Does anyone know if I am going in the right direction with this or point me in the correct direction?

谢谢!

推荐答案

您还可以选择使用-subarrayWithRange: /Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/doc/uid/20000137-BABDBFIA"rel =" noreferrer> NSArray 文档:

You also have the option of using -subarrayWithRange: detailed in the NSArray documentation:

NSArray *firstHalfOfArray;
NSArray *secondHalfOfArray;
NSRange someRange;

someRange.location = 0;
someRange.length = [wholeArray count] / 2;

firstHalfOfArray = [wholeArray subarrayWithRange:someRange];

someRange.location = someRange.length;
someRange.length = [wholeArray count] - someRange.length;

secondHalfOfArray = [wholeArray subarrayWithRange:someRange];

此方法返回新的autorelease -d数组.

This method returns new, autorelease-d arrays.

这篇关于如何将NSArray分成两个相等的部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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