将对象数组分为4组-iOS [英] split array of objects into groups of 4 - ios
本文介绍了将对象数组分为4组-iOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将对象数组拆分为对象数组?
How do you split an array of objects into an array of array of objects?
说我想分成4组,该怎么做?
say I want to split into groups of 4, how do I do that?
[a,b,c,d,e,f,g,h] =>[a,b] [c,d] [e,f] [g,h]
[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]
or maybe if I specify that I want to split into groups of 3, then the result should be [a,b,c], [d,e,f], [g,h]
如果h不存在,它也应该工作.
it should also work if h doesn't exist.
推荐答案
尝试以下逻辑.....
Try this logic.....
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]);
这篇关于将对象数组分为4组-iOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文