14

我有一个 NSArray,我想将它分成两个相等的部分(如果奇数“计数”然后添加到后一个新数组) - 我想将它拆分为“中间”可以这么说。

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

// 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 方法或一些快速枚举方法来完成上述代码?但我无法让以下代码工作(或其他变体):

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

有谁知道我是否朝着正确的方向前进或指出我正确的方向?

谢谢!

4

3 回答 3

45

您还可以选择使用文档-subarrayWithRange:中的详细NSArray信息:

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 数组。

于 2009-11-20T03:18:47.783 回答
2

您是否尝试过添加nil-initWithObjects:方法的末尾?

NSArray *leftArray = [[NSArray alloc] initWithObjects:[testableArray objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(????, ????)]], nil];
NSArray *rightArray = [[NSArray alloc] initWithObjects:[testableArray objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(????, ????)]], nil];
于 2009-11-20T03:12:26.920 回答
0

如果您想在第一个数组上添加一个额外的对象(以防总项目为奇数),请使用从 Alex 的答案修改的以下代码:

NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", nil];
//NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", @"B", nil];
//NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", @"B", @"C", nil];
//NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", @"B", @"C", @"D", nil];
//NSArray *arrayTotal = [NSArray arrayWithObjects:@"A", @"B", @"C", @"D", @"E", nil];

NSArray *arrLeft;
NSArray *arrRight;

NSRange range;
range.location = 0;
range.length = ([arrayTotal count] % 2) ? ([arrayTotal count] / 2) + 1 : ([arrayTotal count] / 2);

arrLeft = [arrayTotal subarrayWithRange:range];

range.location = range.length;
range.length = [arrayTotal count] - range.length;

arrRight = [arrayTotal subarrayWithRange:range];

NSLog(@"Objects: %lu", (unsigned long)[arrLeft count]);
NSLog(@"%@", [arrLeft description]);

NSLog(@"Objects: %lu", (unsigned long)[arrRight count]);
NSLog(@"%@", [arrRight description]);
于 2017-08-22T11:26:59.757 回答