Skip to content

Instantly share code, notes, and snippets.

@vikingosegundo
Last active August 29, 2015 14:01
Show Gist options
  • Save vikingosegundo/1d6692b5a26e9e0d8a81 to your computer and use it in GitHub Desktop.
Save vikingosegundo/1d6692b5a26e9e0d8a81 to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h>
@interface Item : NSObject
@property NSInteger itemID;
@property NSInteger typeID;
@property(copy) NSString *itemDescription;
@end
@implementation Item
-(NSString *)description
{
return [NSString stringWithFormat:@"Item: %li, typeID: %li, description: %@", (long)self.itemID, (long)self.typeID, self.itemDescription];
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSArray *data =@[ @{@"itemID": @1, @"typeID": @7, @"description": @"some text 1"},
@{@"itemID": @2, @"typeID": @7, @"description": @"some text 2"},
@{@"itemID": @3, @"typeID": @5, @"description": @"some text 3"},
@{@"itemID": @4, @"typeID": @5, @"description": @"some text 4"},
@{@"itemID": @5, @"typeID": @8, @"description": @"some text 5"}];
NSMutableArray *items = [@[ ] mutableCopy];
[data enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
[items addObject:({
Item *item = [[Item alloc] init];
item.itemID = [obj[@"itemID"] integerValue];
item.typeID = [obj[@"typeID"] integerValue];
item.itemDescription = obj[@"description"];
item;
})];
}];
NSMutableDictionary *itemsByType = [@{} mutableCopy];
[items enumerateObjectsUsingBlock:^(Item *item, NSUInteger idx, BOOL *stop) {
id key = @(item.typeID);
if (![[itemsByType allKeys] containsObject:key]) {
itemsByType[key] = [@[] mutableCopy];
}
[itemsByType[key] addObject:item];
}];
[itemsByType enumerateKeysAndObjectsUsingBlock:^(id key, NSMutableArray *items, BOOL *stop) {
[items sortUsingComparator:^NSComparisonResult(Item *item1, Item *item2) {
return item1.itemID < item2.itemID;
}];
}];
NSMutableArray *resultArray = [@[] mutableCopy];
[[itemsByType allKeys] enumerateObjectsUsingBlock:^(id key, NSUInteger idx, BOOL *stop) {
[resultArray addObject:itemsByType[key][0]];
}];
[resultArray sortUsingComparator:^NSComparisonResult(Item *item1, Item *item2){
return item1.itemID > item2.itemID;
}];
NSLog(@"%@", resultArray);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment