how to sort an NSMutableArray of Arrays?
I'm trying to sort an array of a table view with no luck, this is how I'm trying to do it:
开发者_开发技巧- (void) compare
{
NSMutableArray *temp = [[NSMutableArray alloc] initWithObjects: nil];
[temp addObjectsFromArray:[self displayedObjects]];
int a = [[self displayedObjects] count];
for (int i = 0; i < (a - 1); i++){
for (int j = 0; j <= (i^2); j++) {
NSString *temp1 = [temp objectAtIndex:i];
NSString *temp2 = [temp objectAtIndex:i+1];
if (temp1 > temp2) {
[movieIndex replaceObjectAtIndex:i withObject:temp2];
[movieIndex replaceObjectAtIndex:i+1 withObject:temp1];
}
}
}
[self movieIndex];
[[self tableView] reloadData];
}
displayedObjects
is an array of array that the user can add new objects. this objects are movie instances in form of:
The tableview cell has the title of the movie. "in" that title there is a tableview with details about the movie. What i want to do is sort the displayed movies titles in ascending order but my code doesn't seem to work.
displayedObjects
is a set of 3 NSStrings and 1 NSNumber. It gets objects form the following class:
#import <Foundation/Foundation.h>
@interface Movie : NSObject
{
NSString *_title;
NSString *_gender;
NSString *_location;
NSNumber *_publicationYear;
}
@property (nonatomic, retain) NSString *location;
@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSString *gender;
@property (nonatomic, retain) NSNumber *publicationYear;
+ (id)movieWithTitle:(NSString *)title
gender:(NSString *)gender
year:(NSUInteger)year
location:(NSString *)location;
- (id)initWithTitle:(NSString *)title
gender:(NSString *)gender
year:(NSUInteger)year
location:(NSString *)location;
@end
Because no one has suggested it yet, and I personally love blocks, I'll suggest the block alternative to the same thing already suggested:
[myArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
...
}];
I made it work by using:
NSSortDescriptor *titleSorter= [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
[movieIndex sortUsingDescriptors:[NSArray arrayWithObject:titleSorter]];
精彩评论