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



我有以下可变数组:

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:@" "]);

但我在返回行中收到一条"Bad receiver type'NSInteger'(又名'long')"错误消息。此外,我在NSLog行中有一条警告:"Format指定类型为'long',但参数的类型为'NSString*'"。我该如何修复它?

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

[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值来相应地表示对象的顺序。

您正试图在不是对象的NSInteger上调用compare:;它是整数类型的typedef(intlong取决于体系结构)。

此外,componentsJoinedByString:返回一个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:@" "]);

关于"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"是长的格式字符串(正如警告所说),但-componentsSeparatedByString:返回一个NSString对象。任何Objective-C对象的正确格式字符串都是@"%@",因此该行应该读取NSLog(@"%@", [persons componentsJoinedByString:@" "]);

就像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;
            } 
    }
 ];
[YOURMutableArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

相关内容

  • 没有找到相关文章

最新更新