【问题标题】:Sorting an Array of custom objects by a dictionary included in the custom object: How?通过自定义对象中包含的字典对自定义对象数组进行排序:如何?
【发布时间】:2009-12-05 05:08:10
【问题描述】:

我有一组自定义对象。对象包括字典。 像这样的:

CustomDataModel *dataModel;

dataModel.NSString
dataModel.NSDictionary
dataModel.image

我想按字典中的一个对象排序:

dataModel.NSDictionary ObjectWithkey=@"Name"

dataModel 被加载到一个 NSArray 中。我现在想按字典中的 @"Name" 键排序。这是 NSSortDescriptor 可以处理的吗?基本排序工作正常,只是还没有弄清楚这个......

【问题讨论】:

    标签: iphone objective-c nssortdescriptor


    【解决方案1】:

    你的问题对我来说并不完全清楚,但你可以在你的 NSArray 上尝试这样的事情:

    - (NSArray *)sortedItems:(NSArray*)items;
    {
        NSSortDescriptor *sortNameDescriptor = 
                            [[[NSSortDescriptor alloc] 
                              initWithKey:@"Name" ascending:NO] 
                              autorelease];
    
        NSArray *sortDescriptors = 
                            [[[NSArray alloc] 
                              initWithObjects:sortNameDescriptor, nil] 
                              autorelease];
    
        return [items sortedArrayUsingDescriptors:sortDescriptors];
    }
    

    【讨论】:

    • 这也是我想出的解决方案,但是,由于 NSDictionary,我一开始并不确定它是否会起作用。无论如何,像魅力一样工作!感谢您的帮助和确认,马特。
    【解决方案2】:
    //Sort an array which holds different dictionries - STRING BASED   - Declare it in the .h
        - (NSArray *)sortStringsBasedOnTheGivenField:(id)dictionaryKey arrayToSort:(NSMutableArray *)arrayToHoldTemp ascending:(BOOL)ascending {
            NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:dictionaryKey ascending:ascending selector:@selector(localizedCaseInsensitiveCompare:)] ;
            NSArray *descriptors = [NSArray arrayWithObject:nameDescriptor];
            [arrayToHoldTemp sortUsingDescriptors:descriptors];
            [nameDescriptor release];
            return arrayToHoldTemp;
        }
    

    用法:

    self.mainArrayForData = [NSArray arrayWithArray:[self sortNumbersBasedOnTheGivenField:@"Name" arrayToSort:arrayWhichContainsYourDictionries ascending:YES]];
    

    上述方法适用于存放字典的数组

    【讨论】:

      猜你喜欢
      • 2010-10-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2018-05-12
      • 1970-01-01
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      相关资源
      最近更新 更多