Grouping of Custom Objects in Objective-C

前端 未结 6 1630
伪装坚强ぢ
伪装坚强ぢ 2021-01-12 03:59

I have and array of custom objects of Person Class

Person : NSObject{
    NSString *firstName;
    NSString *lastName; 
    NSString *age;
}

NSMutableArray          


        
6条回答
  •  时光取名叫无心
    2021-01-12 04:53

    - (NSDictionary *)groupObjectsInArray:(NSArray *)array byKey:(id  (^)(id item))keyForItemBlock
    {
        NSMutableDictionary *groupedItems = [NSMutableDictionary new];
        for (id item in array)
        {
            id  key = keyForItemBlock(item);
            NSParameterAssert(key);
    
            NSMutableArray *arrayForKey = groupedItems[key];
            if (arrayForKey == nil)
            {
                arrayForKey = [NSMutableArray new];
                groupedItems[key] = arrayForKey;
            }
            [arrayForKey addObject:item];
        }
        return groupedItems;
    }
    

提交回复
热议问题