如何对NSMutableArray数组进行排序?

时间:2011-07-02 14:42:51

标签: iphone sorting nsmutablearray

我正在尝试排序一个没有运气的表格视图数组,这就是我试图这样做的方法:

    - (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是一个数组数组,用户可以添加新对象。这个对象是以下形式的电影实例:

tableview单元格具有电影的标题。 “在”该标题中有一个包含电影细节的桌面视图。我想要做的是按升序对显示的电影标题进行排序,但我的代码似乎不起作用。


displayedObjects是一组3个NSStrings和1个NSNumber。它从以下类获取对象:

#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

2 个答案:

答案 0 :(得分:0)

因为还没有人建议它,而且我个人喜欢积木,我会建议替代已经建议的同样的东西:

[myArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
     ...
}];

答案 1 :(得分:0)

我通过使用:

使其成功
NSSortDescriptor *titleSorter= [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];

[movieIndex sortUsingDescriptors:[NSArray arrayWithObject:titleSorter]];