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
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.
For example:
//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
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]];
After this, your scores
array will be sorted by the score ascending.