使用sortOrder对NSMutableDictionary进行排序

时间:2012-03-19 12:07:59

标签: iphone uitableview core-data nsmutabledictionary

对于已分区的tableView,我需要按category.sortOrder

对书籍进行排序
    NSMutableDictionary *theDictionary = [NSMutableDictionary dictionary];
    for (Book *object in self.books) {            
        NSMutableArray *theMutableArray = [theDictionary objectForKey:object.category.categoryName];
        if ( theMutableArray == nil ) {
            theMutableArray = [NSMutableArray array];
            [theDictionary setObject:theMutableArray forKey:object.category.categoryName];
        }
        [theMutableArray addObject:object];
    }
    self.sections = [[theDictionary allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

如何在我的词典中包含category.sortOrder值,以便我可以正确排序我的部分?

1 个答案:

答案 0 :(得分:1)

为清楚起见,您应该创建一个类来保存每个部分的值,然后将它们添加到您的字典中。如果您不想要额外的文件,可以在控制器中完成所有操作,但如果您需要,也可以创建另一个文件:

@interface TableSection
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *order;
@property (nonatomic, retain) NSArray *objects;
@end

@implementation TableSection
@synthesize name;
@synthesize order;
@synthesize objects;
@end


NSMutableDictionary *sections = [NSMutableDictionary dictionary];
for (Book *object in self.books) {
    TableSection *section = [categories objectForKey:object.category.categoryName];
    if ( section == nil ) {
        section = [[TableSection alloc] init];
        section.name = object.category.categoryName;
        section.order = object.category.sortOrder;
        section.objects = [NSMutableArray array];
        [sections setObject:section forKey:object.category.categoryName];

    }
    [(NSMutableArray *)section.objects addObject:object];
}
self.sections = [[categories allValues] sortUsingDescriptors:
                 [NSArray arrayWithObject:
                  [NSSortDescriptor descriptorWithKey:@"order" ascending:YES]]];