2011-07-02 67 views
1

我想排序沒有運氣表視圖的數組,這就是我正在努力做到這一點:如何排序數組的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 

回答

0

因爲沒有人認爲它,但我個人喜歡的塊,我會建議塊替代已經提出了同樣的事情:

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

我也試過你的方法[movieIndex sortUsingComparator:^ NSComparisonResult(ID OBJ1,ID OBJ2){ 的NSString * name1 = obj1; NSString * name2 = obj2; return [name1 localizedCaseInsensitiveCompare:name2]; } ];但我得到一個sigbart錯誤「終止應用程序由於未捕獲的異常'NSInvalidArgumentException',原因:' - [電影localizedCaseInsensitiveCompare:]:無法識別的選擇發送到實例0x5912da0'」 – Morpheas1983

+0

這與我的提議沒有任何關係......只是你的「...」的實現。 – Steve

0

我把它用工作:

NSSortDescriptor *titleSorter= [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES]; 

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