iPhone Obj C — Sorting a Mutable Array of dictionaries — display a string but sort by value

六月ゝ 毕业季﹏ 提交于 2020-01-01 06:37:07

问题


I have a NSMutableArray with 30 dictionaries inside of it. Each contains a name and a value. I currently have the names sorted so that the show in a table view alphabetically. However, I'd like to make a UIButton to give the option of STILL DISPLAYING THE NAMES, but ordered by the value. The value doesn't need to be displayed. Also, where in the .m/.h files would these codes be placed? THANKS!


回答1:


To be able to help you I need a test data to work with. Let's say your array with data looks like this:

NSMutableArray *aMutableArray = [NSMutableArray arrayWithObjects:
         [NSDictionary dictionaryWithObjectsAndKeys:
          @"A", @"name",
          [NSNumber numberWithInt:6], @"value", nil],
         [NSDictionary dictionaryWithObjectsAndKeys:
          @"C", @"name",
          [NSNumber numberWithInt:2], @"value", nil],
         [NSDictionary dictionaryWithObjectsAndKeys:
          @"B", @"name",
          [NSNumber numberWithInt:4], @"value", nil], nil];

In this case case here's how you sort it by value:

NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"value" ascending:YES];
[aMutableArray sortUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]];

As for where to place this code place it wherever you need the reordering to happen (in the implementation [.m] file of course).

HTH and if there will be any questions ask them in the comments.



来源:https://stackoverflow.com/questions/2149069/iphone-obj-c-sorting-a-mutable-array-of-dictionaries-display-a-string-but

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!