Search code examples
iosobjective-cnsarraynsdictionary

Split nsarray to nsdictionary


I am quering Parse and get an array back

PFQuery *query = [Points query];
[query whereKey:@"city" equalTo:[SharedParseStore sharedStore].chosenCity];
query.cachePolicy = kPFCachePolicyCacheThenNetwork;

I want to sort the array into a dictionary based on the district value that is in the Point object so that i can use a tableview with sections (district section names)

[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];

    for (Points *point in objects) {
        [dict setValue:point forKey:point.district];
    }            
        block(dict, error);
    } else {

        NSLog(@"Error: %@ %@", error, [error userInfo]);
    }
}];

The problem is it only adds 1 value of course

So to make it easy to understand: The objects coming from Parse are Point objects with the following property's: Name,District,City

I want to create a NSdictionary with the districts (so I need to collect them out of the objects first because I don't know them) as a key and the value for that key is an array with the points that are in that district.

I don't know beforehand what the districts will be. They will need to be picked from the objects array that is returned from Parse.

My final object I want to create is a nsdictionary with arrays of points for every distinct district(that is the key).

Example: [@"districtA" : an array with Point objects that have districtA in their district property, etc etc]

what is the best way to do this because i really can't see how to do it ?


Solution

  • You answered your own question when you say:

    I want to create a NSdictionary with the districts as a key and the value for that key is an array with the points that are in that district.

    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            NSMutableDictionary *dict = [@{} mutableCopy];
    
            for (Points *point in objects) {
                // if no point for that district was added before,
                // initiate a new array to store them
                if (![dict containsKey:point.district])
                    dict[point.district] = [@[] mutableCopy];
    
                [dict[point.district] addObject:point];
            }     
    
            block(dict, error);
    
        } else {
            NSLog(@"Error: %@ %@", error, [error userInfo]);
        }
    }];