简体   繁体   English

用对象对NSArray进行排序

[英]sort NSArray with objects

Supposing NSArray has several objects which belong to two classes, 假设NSArray有几个属于两个类的对象,

@interface FWNewsObj:NSObject
 {
  NSString *newsTitle;
  NSDate *newsTime;
 }
 @end




@interface FWPhotoObj:NSObject
 {
  NSString *photoTitle;
  NSDate *photoTime;
 }
 @end

I'd like to sort the NSArray with object's title (or time). 我想用对象的标题(或时间)对NSArray进行排序。 However the title variable in each class has different names. 但是,每个类中的title变量具有不同的名称。

Then How can I do the sort? 那我该怎么办呢? Thanks. 谢谢。

What is instantly coming to my mind is(If I am understanding the Q correctly) : 我马上想到的是(如果我正确理解了Q):

  • 1st create a dictionary, with titleNames as the keys, and value as the objects 1创建一个字典,将titleNames作为键,并将value作为对象
  • Sort the keys array simply 简单地对键数组进行排序
  • Then create a sorted array of objects pulling them out of the dictionary, on basis of this sorted keys array 然后,基于此排序的键数组,创建一个排序的对象数组,将其从字典中拉出

You have to write a custom compare method that both your classes implement. 您必须编写两个类都实现的自定义比较方法。 It must take one object as a parameter and return an NSComparisonResult ( NSOrderedAscending , NSOrderedDescending or NSOrderedSame ) 它必须将一个对象作为参数并返回NSComparisonResultNSOrderedAscendingNSOrderedDescendingNSOrderedSame

You can then use sortedArrayUsingSelector: with your own comparison method. 然后,您可以将sortedArrayUsingSelector:与自己的比较方法一起使用。

Example: 例:

In FWNewsObj: 在FWNewsObj中:

- (NSComparisonResult)compareTitle:(id)obj
{
    NSAssert([obj isKindOfClass:[FWNewsObj class]] || [obj isKindOfClass:[FWPhotoObj class]], @"Don't know how to compare %@ to %@", self, obj);
    if ([obj isKindOfClass:[FWPhotoObj class]]) {
        return [newsTitle compare:[(FWPhotoObj *)obj photoTitle]];
    } else {
        return [newsTitle compare:[(FWNewsObj *)obj newsTitle]];
    }
}

In FWPhotoObj: 在FWPhotoObj中:

- (NSComparisonResult)compareTitle:(id)obj
{
    NSAssert([obj isKindOfClass:[FWNewsObj class]] || [obj isKindOfClass:[FWPhotoObj class]], @"Don't know how to compare %@ to %@", self, obj);
    if ([obj isKindOfClass:[FWPhotoObj class]]) {
        return [photoTitle compare:[(FWPhotoObj *)obj photoTitle]];
    } else {
        return [photoTitle compare:[(FWNewsObj *)obj newsTitleTitle]];
    }
}

It would actually be easier to just define a title method in both classes that wraps either the photoTitle or the newsTitle. 在两个类中同时包装photoTitle或newsTitle的title方法实际上会更容易。 Then you can just use NSSortDescriptor with title as the key. 然后,您可以使用title为键的NSSortDescriptor

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM