首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSMutableArray的排序、存储桶排序和排序存储桶

NSMutableArray的排序、存储桶排序和排序存储桶
EN

Stack Overflow用户
提问于 2012-03-09 15:30:07
回答 1查看 303关注 0票数 0

我有一个ObjectNSArray,它有一个有趣的property,我想通过以下方式使用它:

Object1 - Property AObject2 - Property AObject3 - Property BObject4 - Property DObject5 - Property DObject6 - Property D

我希望将它们按属性进行存储桶排序,放入新的数组中:

Array1 - Objects Object1, Object2

Array2 - Objects Object3

Array3 - Objects Object 4, Object5, Object6

然后在每个数组中,使用timeStamp属性进行排序。

我试图通过创建一个字典来实现这一点,通过像if ([dictionary objectForKey:@"propertyVal"]) //add object else // create array for key, add object to array这样的属性向字典添加有趣的对象。这种方法并没有像预期的那样工作,因为我最终需要使用allKeysForValue来解除NSMutableDictionary的密钥,这是不可靠的。

我觉得这是一个相当普遍的问题,我希望听到任何关于我如何解决这个问题的见解。代码很棒,但即使是一个算法(使用适当的对象)也应该足够了。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-03-09 15:42:55

这不是一种适当的存储桶排序,但应该适用于一组三个属性。稍微摆弄一下,你应该能够为任意数量的属性调整它:

编辑。我做了一个动态版本(只需将属性类型设置为您需要的类型):

代码语言:javascript
复制
- (NSMutableArray *)order:(NSDictionary *)objects byProperty:(id)property {
    NSMutableSet *propertySet = [NSMutableSet setWithCapacity:5]; // so we can count the unique properties
    for (Object *obj in [objects allValues]) {
        [propertySet addObject:[obj property]];
    }

    NSMutableArray *objectCollections = [NSMutableArray arrayWithCapacity:[propertySet count]];

    // create arrays for every property
    for (int i = 0; i < [objects allValues]; i++) {
        NSMutableArray *collection = [NSMutableArray arrayWithCapacity:5];
        [objectCollections addObject:collection];
    }  
    NSArray *allProperties = [propertySet allObjects];

    // push objects into arrays according to a certain property
    for (Object *obj in [dictionary allValues]) {
        [[objectCollections objectAtIndex:[allProperties indexOfObject:[obj property]] addObject:obj];
    }

    NSMutableArray *result = [NSMutableArray arrayWithCapacity:[objectCollections count]];
    // sort arrays by timestamp
    for (int i = 0; i < [objectCollections count]; i++) {
            [result addObject:[[objectCollections objectAtIndex:i] sortedArrayUsingComparator:^(id obj1, id obj2) {
            if ([(Object *)obj1 timeStamp] > [(Object *)obj2 timeStamp]) {
                return (NSComparisonResult)NSOrderedAscending;
            }
            if ([(Object *)obj1 timeStamp] < [(Object *)obj2 timeStamp]) {
                return (NSComparisonResult)NSOrderedDescending;
            }            
            return (NSComparisonResult)NSOrderedSame;
        }];
    }
    return result;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9630454

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档