I need to split one NSArray
into NSDictionary
. Every key in NSDictionary
will contain an NSArray
with the object with the same value.
i.e. I have an array with 1000 customers and I want create an NSDictionary
based on their zip code.
I wrote this code into an NSArray
category and it works, but I'm looking for a better name and a way (if it exists) to do the same job with the KVC.
-(NSDictionary *)groupArrayWithBlock:(id<NSCopying> (^)(id obj))block {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
for (id obj in self) {
id<NSCopying> key = block(obj);
if (! dictionary[key]) {
NSMutableArray *arr = [NSMutableArray array];
dictionary[key] = arr;
}
[dictionary[key] addObject:obj];
}
return [dictionary copy];
}