对包含NSMutableArrays的NSMutableArra

对包含NSMutableArrays的NSMutableArra

本文介绍了Objective-C:对包含NSMutableArrays的NSMutableArray进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm currently using NSMutableArrays in my developments to store some data taken from an HTTP Servlet.

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

Everything is fine since now I have to sort what is in my array.

这就是我要做的:

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]];

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

First column contain a Label and 2nd one is a score I want the array to be sorted descending.

我存储数据的方式好吗?有没有比在NSMutableArray中使用NSMutableArrays更好的方法了?

Is the way I am storing my data a good one ? Is there a better way to do this than using NSMutableArrays in NSMutableArray ?

我是iPhone开发人员的新手,我已经看过一些有关排序的代码,但对此感觉不太好.

I'm new to iPhone dev, I've seen some code about sorting but didn't feel good with that.

提前感谢您的回答!

推荐答案

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

This would be much easier if you were to create a custom object (or at least use an NSDictionary) to store the information, instead of using an array.

例如:

//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

一旦您填充了scores阵列,就可以执行以下操作:

Once you've populated your scores array, you can now do:

//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]];

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

After this, your scores array will be sorted by the score ascending.

这篇关于Objective-C:对包含NSMutableArrays的NSMutableArray进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 13:12