2012-01-27 72 views
-2

enter image description hereNSMutableArray排序

我在單元格中有5個NSMutableArrays。我需要通過一個值對單元格進行排序。 例子我需要按時間對細胞進行排序。

[MyArray1 sortUsingSelector:@selector(compare:)]; 

但我將如何與其他4個NSMutableArray在單元格?

+0

你應該直接上傳圖片到計算器,還有對「共享」網站 – Bogatyr 2012-01-27 12:31:16

+0

他沒有足夠的信譽來這樣做 – vikingosegundo 2012-01-27 12:37:38

+0

我上傳的各種垃圾,但我不能這樣做了後,我的名譽1 – Pavel 2012-01-27 12:37:55

回答

5

這不是爲你的細胞數據存儲在5個陣列,不要把它們分開是個好主意;創建一個數據容器類,將每個單元格的所有值存儲在一個數據容器對象中,然後可以使用其中一個值對數據容器進行排序。

如:

DataContainer.h:

@interface DataContainer : NSObject 
{ 
    NSDate *date1; 
    NSDate *date2; 
    NSString *upperTitle; 
    NSString *mainTitle; 
    NSString *subtitle; 
} 

@property (nonatomic, strong) NSDate *date1; 
@property (nonatomic, strong) NSDate *date2; 
@property (nonatomic, strong) NSString *upperTitle; 
@property (nonatomic, strong) NSString *mainTitle; 
@property (nonatomic, strong) NSString *subtitle; 

@end 

DataContainer.m:

@implementation DataContainer 
@synthesize date1, date2, upperTitle, mainTitle, subtitle; 
@end 

然後你就可以創建你DataContainer的(每個細胞),並把它們存儲在oneNSMutableArray

如:

DataContainer *container = [[DataContainer alloc] init]; 
[container setDate1:[NSDate date]]; 
[container setMainTitle:@"blahblah"]; 
///... 
[cellArr addObject:container]; 

排序這個數組,使用:

cellArr = [cellArr sortedArrayUsingComparator:^(id cont1, id cont2) { 
       return [[(DataContainer *) cont1 date1] compare:[(DataContainer *) cont2 date1]]; 
      }]; 

,然後用它們在你的cellForRowAtIndexPath:

DataContainer *container = [cellArr objectAtIndex:indexPath.row]; 
//container.date1, container.date2, container.upperTitle, container.mainTitle and container.subtitle are the values that you need for your cell. 

注意到,此代碼是合適的,如果你」爲您的項目重新使用ARC(自動引用計數);如果你不使用ARC,那麼你需要在屬性定義改變strongretain並添加release年代到需要的地方,以避免內存泄漏。

+0

,但我可以排序單元格,如果我有例子,MyArray1,MyArray2,MyArray3,MyArray4,MyArray5在單元格? – Pavel 2012-01-27 12:50:31

+0

爲什麼你需要這五個陣列?在UITableViewCell中顯示數據是一種非常糟糕的方式。 – 2012-01-27 12:59:13

+0

如果我將修改我的代碼,做一流的數據會很長 – Pavel 2012-01-27 15:11:36

1

我同意安德烈。你把你的數組中的所有東西都粘在容器中,然後你對容器進行排序。 您的容器應該包含您在一個單元格中存儲的所有內容(日期,時間,文本,text2,英語/數學等)。

然後你排序細胞容器陣列。

  cellArr = [cellArr sortedArrayUsingComparator:^(id cont1, id cont2) { 
       // if date in container 1 is earlier than in container 2 
       return (NSComparisonResult)NSOrderedDescending; 
       // if date is later 
       return (NSComparisonResult)NSOrderedAscending; 
       // if none of the above 
       return (NSComparisonResult)NSOrderedSame; 
      }]; 
+0

我的類的示例名稱是MyClass,數組的名稱是MyArray1,MyArray2,MyArray3,MyArray4,MyArray5。可以寫我代碼如何看起來像? – Pavel 2012-01-27 15:42:01

+0

@Pavel:請仔細閱讀上面的答案。您需要**來創建一個數據容器,然後才能按照需要對容器中的所有數據進行排序。 – 2012-01-27 18:19:00

+0

@Pavel:這足夠清楚了嗎?你需要任何代碼示例嗎? – 2012-01-27 18:19:32