Objective-C:对包含NSMutableArrays的NSMutableArray进行排序

Dou*_*ugh 6 sorting objective-c nsmutablearray

我目前正在使用NSMutableArrays我的开发来存储从HTTP Servlet获取的一些数据.

一切都很好,因为现在我必须对我的数组中的内容进行排序.

这就是我做的:

NSMutableArray *array = [[NSMutableArray arrayWithObjects:nil] retain];
[array addObject:[NSArray arrayWithObjects: "Label 1", 1, nil]];
[array addObject:[NSArray arrayWithObjects: "Label 2", 4, nil]];
[array addObject:[NSArray arrayWithObjects: "Label 3", 2, nil]];
[array addObject:[NSArray arrayWithObjects: "Label 4", 6, nil]];
[array addObject:[NSArray arrayWithObjects: "Label 5", 0, nil]];
Run Code Online (Sandbox Code Playgroud)

第一列包含Label,第二列是我希望数组按降序排序的分数.

我存储数据的方式是好的吗?有没有更好的办法做到这一点比使用NSMutableArraysNSMutableArray

我是iPhone开发人员的新手,我看过一些关于排序的代码,但对此并不满意.

提前感谢您的回答!

Dav*_*ong 10

如果您要创建自定义对象(或至少使用an NSDictionary)来存储信息而不是使用数组,这将更容易.

例如:

//ScoreRecord.h
@interface ScoreRecord : NSObject {
  NSString * label;
  NSUInteger score;
}
@property (nonatomic, retain) NSString * label;
@property (nonatomic) NSUInteger score;
@end

//ScoreRecord.m
#import "ScoreRecord.h"
@implementation ScoreRecord 
@synthesize label, score;

- (void) dealloc {
  [label release];
  [super dealloc];
}

@end

//elsewhere:
NSMutableArray * scores = [[NSMutableArray alloc] init];
ScoreRecord * first = [[ScoreRecord alloc] init];
[first setLabel:@"Label 1"];
[first setScore:1];
[scores addObject:first];
[first release];
//...etc for the rest of your scores
Run Code Online (Sandbox Code Playgroud)

一旦填充了scores阵列,您现在可以:

//the "key" is the *name* of the @property as a string.  So you can also sort by @"label" if you'd like
NSSortDescriptor * sortByScore = [NSSortDescriptor sortDescriptorWithKey:@"score" ascending:YES];
[scores sortUsingDescriptors:[NSArray arrayWithObject:sortByScore]];
Run Code Online (Sandbox Code Playgroud)

在此之后,您的scores数组将按分数升序排序.


Sim*_*ide 5

您不需要为如此微不足道的事情创建自定义类,这是浪费代码.你应该使用一个NSDictionary's 的数组(ObjC中的字典=其他语言的哈希).

像这样做:

  NSMutableArray * array = [NSMutableArray arrayWithObjects:
                            [NSDictionary dictionaryWithObject:@"1" forKey:@"my_label"],
                            [NSDictionary dictionaryWithObject:@"2" forKey:@"my_label"],
                            [NSDictionary dictionaryWithObject:@"3" forKey:@"my_label"],
                            [NSDictionary dictionaryWithObject:@"4" forKey:@"my_label"],
                            [NSDictionary dictionaryWithObject:@"5" forKey:@"my_label"],
                            nil];
  NSSortDescriptor * sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"my_label" ascending:YES] autorelease];
  [array sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
Run Code Online (Sandbox Code Playgroud)