Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

NSMutableArray - add data to specific object

I have two NSMutableArray in my project with name:

  • weeks
  • post

i receive the the data from back-end in JSON. { "posts":[ {"title" : "some title", "w" : "01"}, {"title" : "some title", "w" : "01"}, {"title" : "some title", "w" : "02"} ], "weeks":[ {"w":"01"}, {"w":"52"} ] }

I serialize it and with Dictionary get the data and put it into weeks and posts

How can I build a new NSMutableArray which have the weeks as a key/object and in that alla posts which belongs to it

like:

( 01 = ( {"title" : "some title", "w" : "01"}, {"title" : "some title", "w" : "01"} ), 02 = ( {"title" : "some title", "w" : "02""} ), )

I can do this in the Back-End .. wich I did in the beginning , but I got problem when I try to load more data into my table and update section & rows.

maybe other ways I can pars my posts into the my dynamic table view based on weeks !

thanks !

1 Answer

Take a look at what you want, i.e. (01 = ( {"title"... etc, The outermost level is actually a dictionary, the next level is an array, then finally another dictionary, which is actually your "post" object.

So to construct what you want, you start with NSMutableDictionary, then hash the posts by their "w" element as follow:

NSMutableDictionary * postByWeek = [NSMutableDictionary dictionaryWithCapacity:0];
for ( NSDictionary * aPost in self.post ) {
   NSString * week = aPost[@"w"];
   if ( postByWeek[week] == nil ) { // a dictionary returns nil if the key is not present
       // initialize the new key with an empty NSMutableArray
       postByWeek[week] = [NSMutableArray arrayWithCapacity:1];
   }

  // Add the post to the dictionary
  [postByWeek[week] addObject:aPost]; 
}

yes exactly. so perfect. I added the NSMutableDictionary to the .h file , and initialize it in viewDidLoad once ! i works very nice ;)

thanks a lot for your time, and clean code ;)