简体   繁体   English

使用NSDictionary在UITableview中对数据进行排序

[英]Sort Data in UITableview using NSDictionary

I have an app that I need to support till the original developer comes back. 在原始开发者回来之前,我需要支持一个应用程序。

Basically it has a method that groups the data into sections of UITableView . 基本上,它具有一种将数据分组到UITableView各个部分中的方法。

It all works very nicely and shows the Sections by DogLocation . 一切都很好,并显示了DogLocation的Sections。

This is the code I have : 这是我的代码:

-(void)loadSortedData:(NSString*)breedToLoad fieldToSort:(NSString*)sortField
 {

    self.items = [DbUtilities getDogsByBreed:breedToLoad SortField:sortField];

    NSMutableDictionary * theDictionary = [NSMutableDictionary dictionary];

    for ( Dog * object in self.items )
    {
      NSMutableArray * theMutableArray = [theDictionary objectForKey:object.DogLocation];

      if ( theMutableArray == nil )
      {
        theMutableArray = [NSMutableArray array];
        [theDictionary setObject:theMutableArray forKey:object.DogLocation];
      }

      [theMutableArray addObject:object];

    }

    self.sortedMediaItems = [[theDictionary allKeys]   sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

   /* Save `theDictionary` in an instance variable */
   self.theSource = theDictionary;
   [self.tableView reloadData];

}

I call this method in my ViewDidLoad by using following syntax: 我使用以下语法在ViewDidLoad调用此方法:

[self loadSortedData:@"Cattle" fieldToSort:@"DogLocation"];

What I am trying to achieve is to be able to call this method by passing a value in the method eg so that I can sort it by other fields and not just the DogLocation eg DogAge,DogPrice . 我要实现的目标是能够通过在方法中传递一个值来调用此方法,例如,以便我可以按其他字段(而不是仅DogLocation)将其排序,例如DogAge,DogPrice。

Could anyone kindly direct me or show me a better way to achieve this instead of writing big if else statement? 有人能指导我或向我展示一种更好的方法来实现这一目标,而不是大声疾呼吗?

Thank you in advance. 先感谢您。

您可以尝试使用M13OrderedDictionary,它基于NSObject而不是NSDictionary,但是可以完成所需的工作: https : //github.com/Marxon13/M13OrderedDictionary

As long as sortField is always a valid property of Dog , you can use Key-Value Coding . 只要sortField始终是Dog的有效属性,就可以使用键值编码

for ( Dog * object in self.items )
{
  id key = [object valueForKey:sortField];
  NSMutableArray * theMutableArray = [theDictionary objectForKey:key];

  if ( theMutableArray == nil )
  {
    theMutableArray = [NSMutableArray array];
    [theDictionary setObject:theMutableArray forKey:key];
  }

  [theMutableArray addObject:object];
}

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

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