新手问题,
我正在玩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?
谢谢!
答案 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:)];
}
希望它有所帮助。