对NSMutableArray进行排序包含Objective C中的NSMutableString

时间:2014-02-14 03:29:16

标签: ios objective-c nsmutablearray nsmutablestring

新手问题,

我正在玩NSMutableArray * myBook,其中包含卡片元素(姓名和电子邮件地址)。

我希望myBook以降序列表显示。

AddressBook.h

#import <Foundation/Foundation.h>
#import "AddressCard.h"
@interface AddressBook : NSObject

@property (nonatomic, copy) NSMutableString *bookName;

@property (nonatomic , strong) NSMutableArray *book;

AddressCard.h

#import <Foundation/Foundation.h>

@interface AddressCard : NSObject

@property (nonatomic, copy) NSMutableString *name, *email;

AddressBook.m

- (void) sort{
    [book sortUsingSelector:@selector(compareNames:)];
}

- (void) showList{

    NSLog(@"====== Contents of: %@ =======",bookName);


    for (AddressCard *theCard in book) {
        NSLog(@"%-20s    %-32s", [theCard.name UTF8String], [theCard.email UTF8String] );
    }

    NSLog(@"===============================");
}

AddressCard.m

- (NSComparisonResult) compareNames: (id) element{


    return [name compare:[element name]];
}

我的CompareNames方法返回升序结果。如何让它返回Descending?

谢谢!

1 个答案:

答案 0 :(得分:4)

虽然- (void)sortUsingSelector:(SEL)comparator方法假设按升序对数组的元素进行排序,但如果数组小于参数,则比较器方法应返回NSOrderedAscending NSOrderedDescending如果数组大于参数,NSOrderedSame如果它们相等。

由于NSComparisonResult定义为:

enum {
   NSOrderedAscending = -1,
   NSOrderedSame,
   NSOrderedDescending
};

typedef NSInteger NSComparisonResult;

你需要的只是一个降序的比较器,如:

- (NSComparisonResult)compareNameInDesendingOrder:(AddressCard *)aCard {
    return -[self.name compare:[aCard name]];
}

- (void)sortInDesendingOrder {
    [book sortUsingSelector:@selector(compareNameInDesendingOrder:)];
}
希望它有所帮助。