• 根据NSArray里边的Object的某个属性进行排序


    假设drinkDetails是一个由Object组成的Array,且Object类有个birthDate属性,我们要根据它来对Array排序。

    方法一

    - (NSComparisonResult)compare:(id)otherObject {
        return [self.birthDate compare:otherObject];
    }
    
    NSArray *sortedArray;
    sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];

    方法二

    NSSortDescriptor *sortDescriptor;
    sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"birthDate"
                                                  ascending:YES] autorelease];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    NSArray *sortedArray;
    sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];

    方法 三
    好了,用第三种方法来个举例子,Object假设是NSDictionary。每个dict里都有一个数字字符串,其key为@”phaseNumber“.
    然后我们按照这个字符串的intValue来排序。起始就一句:

    [array sortUsingFunction:compare context:NULL];

    然后找个地方实现这个compare函数(Function)。如下:

    NSComparisonResult compare(NSDictionary *firstDict, NSDictionary *secondDict, void *context) {
        if ([[firstDict objectForKey:@"phaseNumber"] intValue] < [[secondDict objectForKey:@"phaseNumber"] intValue])
            return NSOrderedAscending;
        else if ([[firstDict objectForKey:@"phaseNumber"] intValue] > [[secondDict objectForKey:@"phaseNumber"] intValue])
            return NSOrderedDescending;
        else
            return NSOrderedSame;
    }

    附上Demo

  • 相关阅读:
    Java中的多线程你只要看这一篇就够了
    模板CodeTemplate
    mybatis_mysql
    Kettle 使用Json输入
    图解ByteBuffer
    双队列缓存
    log4j.properties配置详解与实例
    Kettle 使用Json输入
    JSON响应端模拟测试
    使用Kettle导出excel
  • 原文地址:https://www.cnblogs.com/ligun123/p/2151785.html
Copyright © 2020-2023  润新知