Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten an NSArray

Tags:

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?

like image 470
user23790 Avatar asked Jun 13 '13 12:06

user23790


People also ask

How do you reverse an NSArray?

You can reverse a NSArray by writing your own loop iterating from the end towards the beginning and using a second array to add the items in reverse order. Or you can simply use - (NSEnumerator *)reverseObjectEnumerator from the NSArray class.

Can NSArray contain nil?

arrays can't contain nil.

What is NSArray?

NSArray creates static arrays, and NSMutableArray creates dynamic arrays. You can use arrays when you need an ordered collection of objects. NSArray is “toll-free bridged” with its Core Foundation counterpart, CFArrayRef . See Toll-Free Bridging for more information on toll-free bridging.

Is NSArray ordered?

The answer is yes, the order of the elements of an array will be maintained - because an array is an ordered collection of items, just like a string is an ordered sequence of characters...


2 Answers

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

You may have encountered KVC before in predicates, bindings and similar places, but it can also 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, as discussed here.

like image 109
Monolo Avatar answered Oct 13 '22 23:10

Monolo


Sample Code :

NSMutableArray *mainArray = [[NSMutableArray alloc] init]; for (int i = 0; i < bigArray.count ; i++) {      [mainArray addObjectsFromArray:[bigArray objectAtIndex:i]]; } NSLog(@"mainArray :: %@",mainArray); 
like image 45
Bhavin Avatar answered Oct 13 '22 22:10

Bhavin