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
You don't need to create a custom class for something so trivial, it's a waste of code. You should use an array of NSDictionary
's (dictionary in ObjC = hash in other languages).
Do it like this:
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]];
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.