zoukankan      html  css  js  c++  java
  • 根据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

  • 相关阅读:
    关于栈部分知识点
    面向对象--四则运算
    转型第一步
    输入输出文件版本——计算题
    作业二
    2017《面向对象程序设计》课程作业一
    第四次作业
    light oj 1079
    Light oj 1080
    Codeforces 486B OR in Matrix【水题】
  • 原文地址:https://www.cnblogs.com/ligun123/p/2151785.html
Copyright © 2011-2022 走看看