使用sortUsingComparator对NSMutableArray中的对象进行排序

时间:2012-09-11 12:54:22

标签: objective-c nsmutablearray compare

我有以下可变数组:

NSMutableArray *persons = [[NSMutableArray alloc]initWithObjects:person1, person2, person3, nil];

其中每个人都是一个对象,其中包含(NSInteger)personAge和(NSString *)personName属性。 现在我想通过personAge对这个数组进行排序。所以我尝试了以下内容:

[persons sortUsingComparator:
     ^NSComparisonResult(id obj1, id obj2)
     {
         Person *p1 = (Person*)obj1;
         Person *p2 = (Person*)obj2;

        return [p1.personAge compare: p2.personAge];

     }];

    NSLog(@"%ld", [persons componentsJoinedByString:@" "]);

但是我在返回行中收到“错误接收器类型'NSInteger'(又名'long')”错误消息。另外我在NSLog行中有一个警告:“Format指定类型'long'但参数的类型为'NSString *'”。我该如何解决?

5 个答案:

答案 0 :(得分:36)

不应该使用这样的东西吗?

[persons sortUsingComparator:
      ^NSComparisonResult(id obj1, id obj2){

             Person *p1 = (Person*)obj1;
             Person *p2 = (Person*)obj2;
             if (p1.personAge > p2.personAge) {
                return (NSComparisonResult)NSOrderedDescending;
            }

            if (p1.personAge < p2.personAge) {
                return (NSComparisonResult)NSOrderedAscending;
            }
            return (NSComparisonResult)NSOrderedSame;
    }
];

问题在于您依赖于compare上不存在的NSInteger方法:它只是int的typedef。因此,您希望比较整数值并返回NSComparisonResult值,以相应地表示对象的排序。

答案 1 :(得分:4)

您正试图在compare:上呼叫NSInteger,而int不是对象;它是整数类型的typedef(longcomponentsJoinedByString:,具体取决于架构)。

此外,NSString会返回[persons sortUsingComparator: ^NSComparisonResult(id obj1, id obj2) { Person *p1 = (Person*)obj1; Person *p2 = (Person*)obj2; if (p1.personAge < p2.personAge) return NSOrderedAscending; if (p1.personAge > p2.personAge) return NSOrderedDescending; return NSOrderedSame; }]; NSLog(@"%@", [persons componentsJoinedByString:@" "]); ,而不是整数。

尝试:

{{1}}

答案 2 :(得分:1)

关于“Bad receiver type ...”错误,NSInteger是原始数据类型(不是Objective-C类),因此您无法在其上调用方法。你想要做的是以下几点:

if (p1.personAge > p2.personAge) {
    return (NSComparisonResult)NSOrderedDescending;
}

if (p1.personAge < p2.personAge) {
    return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;

警告是由于@"%ld"是long的格式字符串(如警告所示),但-componentsSeparatedByString:返回NSString个对象。任何Objective-C对象的正确格式字符串为@"%@",因此该行应为NSLog(@"%@", [persons componentsJoinedByString:@" "]);

答案 3 :(得分:0)

[YOURMutableArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

答案 4 :(得分:0)

像tigeguero的回答一样,但更整洁:

 [people sortUsingComparator:
      ^NSComparisonResult(Person* p1, Person* p2){

            if (p1.personAge > p2.personAge) {
                return NSOrderedDescending;
            }
            else if (p1.personAge < p2.personAge) {
                return NSOrderedAscending;
            }
            else{
                return NSOrderedSame;
            } 
    }
 ];