DevC
DevC

Reputation: 7022

Loop through array of objects and add to Array of arrays

I have an array that contains movie objects. These objects are stored in a movie array. My movie object is below.

Movie.h

NSString * name;
NSString * cat_name;

I want to add my original array to a UITableView with dynamic rows and sections but I'm finding it difficult. I think the best way to do this is by having an array of arrays.

For example, there would be an array that contains all horror movies, an array that contains all fiction etc. All in one array. I think that would allow me to get the desired end product. I'm finding it difficult code it though.

EDIT The content of the array is dynamic, so I will not know how many objects will be in it at launch (it's being parsed from JSON). So I need to dynamically create the right amount of sections etc.

Upvotes: 1

Views: 137

Answers (1)

Dani Pralea
Dani Pralea

Reputation: 4551

NSMutableDictionary * mainDictionary = [[NSMutableDictionary alloc] init];

Movie * firstHorrorMovie = [[Movie alloc] init];
firstHorrorMovie.name = @"Psycho";
firstHorrorMovie.cat_name = @"Horror";

Movie * secondHorrorMovie = [[Movie alloc] init];
secondHorrorMovie.name = @"Paranormal Activity";
secondHorrorMovie.cat_name = @"Horror";

Movie * comedyMovie = [[Movie alloc] init];
comedyMovie.name = @"The new guy";
comedyMovie.cat_name = @"Comedy";

NSArray * horrorMovies = [NSArray arrayWithObjects:firstHorrorMovie, secondHorrorMovie, nil];
NSArray * comedyMovies = [NSArray arrayWithObjects:comedyMovie, nil];

[mainDictionary setValue:horrorMovies forKey:@"Horror"];
[mainDictionary setValue:comedyMovies forKey:@"Comedy"];

OR (in your case - dynamically)

NSMutableDictionary * anotherMainDictionary = [[NSMutableDictionary alloc] init];

NSArray * array = [NSArray arrayWithObjects:firstHorrorMovie, secondHorrorMovie, comedyMovie, nil];
for (Movie * movie in array) {
    NSMutableArray * array = [anotherMainDictionary valueForKey:movie.cat_name];
    if (array) {
        [array addObject:movie];
        [anotherMainDictionary setValue:array forKey:movie.cat_name];
    } else {
        NSMutableArray * newArray = [NSMutableArray arrayWithObject:movie];
        [anotherMainDictionary setValue:newArray forKey:movie.cat_name];
    }
}

Upvotes: 3

Related Questions