如何将对象数组拆分为对象数组?
说我想分成4组,我该怎么做?
[a,b,c,d,e,f,g,h] => [a,b] [c,d] [e,f] [g,h]
或者如果我指定我要分成3组,那么结果应该是 [a,b,c],[d,e,f],[g,h]
如果h不存在,它也应该有效。
答案 0 :(得分:2)
试试这个逻辑......
NSArray *arr = [[NSArray alloc]initWithObjects:@"One",@"Two",@"Three",@"Four",@"Five",@"Six",@"Seven",nil];
NSMutableArray *arrNew = [[NSMutableArray alloc]init];
int numberofSubArrs = 3; // change this to check the logic
for (int i=0; i<numberofSubArrs; i++) {
NSMutableArray *arrrr = [[NSMutableArray alloc]init];
[arrNew addObject:arrrr];
}
int m = 0;
for (int k=0; k<[arr count]; k++) {
[[arrNew objectAtIndex:m]addObject:[arr objectAtIndex:k]];
m++;
if (m == numberofSubArrs) {
m=0;
}
}
int g=0;
int p=0;
while(p<[arr count]) {
for (int z=0; z<[[arrNew objectAtIndex:g] count]; z++) {
[[arrNew objectAtIndex:g] replaceObjectAtIndex:z withObject:[arr objectAtIndex:p++]];
}
g++;
}
NSLog(@"Required Array is:%@",[arrNew description]);
答案 1 :(得分:1)
以此为出发点:
NSArray *array = [NSArray arrayWithObjects:@"a", @"b", @"c", @"d", @"e", @"f", @"g", @"h", nil];
NSMutableArray *manyArrays = [NSMutableArray array];
int numberOfElementsInSubArrays = 2;
int numberOfSubArrays = ceil((float)[array count] / (float)numberOfElementsInSubArrays);
for (int i = 0; i < numberOfSubArrays; i++) {
NSMutableArray *subArray = [NSMutableArray array];
for (int j = 0; j < numberOfElementsInSubArrays; j++) {
if (i*numberOfElementsInSubArrays+j < [array count]) {
NSLog(@"Array: %d Value:%@", i, [array objectAtIndex:i*numberOfElementsInSubArrays+j]);
[subArray addObject:[array objectAtIndex:i*numberOfElementsInSubArrays+j]];
}
}
[manyArrays addObject:subArray];
}
答案 2 :(得分:0)
试一试。
NSMutableArray *splitted = [NSMutableArray array];
id firstItem, secondItem;
for (NSInteger i=0; i <= [originalArray count]-1; i+=2) {
@try {
firstItem = [originalArray objectAtIndex:i];
secondItem = [originalArray objectAtIndex:i+1];
}
@catch (NSException *exception) {
secondItem = [NSNull null];
}
@finally {
[splitted addObject:@[firstItem,secondItem]];
}
}