Flatten an NSArray

匿名 (未验证) 提交于 2019-12-03 02:33:02

问题:

I have an array like this:

array: (     (         "http://aaa/product/8_1371121323.png",         "http://aaa/product/14_1371123271.png"     ),     (         "http://aaa/product/9_1371121377.png"     ) ) 

and I have to create another array from that one like this

array: (     "http://aaa/product/8_1371121323.png",     "http://aaa/product/14_1371123271.png",     "http://aaa/product/9_1371121377.png" ) 

How can I do that? Is it possible to combine all the objects and separate them using some string?

回答1:

Sample Code :

NSMutableArray *mainArray = [[NSMutableArray alloc] init]; for (int i = 0; i 


回答2:

It can be done in a single line if you don't mind using key-value coding (KVC). The @unionOfArrays collection operator does exactly what you are looking for.

You may have encountered KVC most often in predicates, bindings and similar places. However, it can be called in normal Objective-C code like this:

NSArray *flatArray = [array valueForKeyPath: @"@unionOfArrays.self"]; 

There are other collection operators in KVC, all prefixed with an @ sign. There is more about it in the docs.



回答3:

Sample code:

NSArray* arrays = @(@(@"http://aaa/product/8_1371121323.png",@"http://aaa/product/14_1371123271.png"),@(@"http://aaa/product/9_1371121377.png")); NSMutableArray* flatArray = [NSMutableArray array]; for (NSArray* innerArray in arrays) {     [flatArray addObjectsFromArray:innerArray]; }  NSLog(@"%@",[flatArray componentsJoinedByString:@","]); 


回答4:

NSMutableArray *arr1 = [NSMutableArray arrayWithArray:[initialArray objectAtIndex:0]]; [arr1 addObjectsFromArray:[initialArray objectAtIndex:1]]; 

Now arr1 contains all the objects



文章来源: Flatten an NSArray
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!