我有一个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(????, ????)]]];
有人知道我是否朝着正确的方向前进,还是指向正确的方向?
谢谢!
答案 0 :(得分:43)
您还可以选择使用NSArray
文档中详述的-subarrayWithRange:
:
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数组。
答案 1 :(得分: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];
答案 2 :(得分: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]);