2013-03-30 63 views
1

我想下面的效果,但我不知道如何使用NSMutableArray結合NSArray超過兩個?關於NSMutableArray添加NS​​Array的問題

1.my代碼

for (int i=0; i<[DateSortArry2 count]; i++) { 
     for (int j=0; j<[DateSortArry2Copy count]; j++) { 
      NSString *sectiondateStr2 = [NSString stringWithFormat:@"%@",[DateSortArry2Copy objectAtIndex:j]];  
      if ([[DateSortArry2 objectAtIndex:i] isEqualToString:sectiondateStr2]) { 
       [Arry addObject:sectiondateStr2]; 
      } 
     } 
     [SumArry addObjectsFromArray:Arry]; 
     [Arry removeAllObjects]; 
    } 

2.my碼結果

SumArry:(
"20130227", 
"20130227", 
"20130227", 
"20130226", 
"20130226", 
"20130226", 
"20130225", 
"20130225") 

3.我想要的結果

SumArry:((
    "20130227", 
    "20130227", 
    "20130227", 
    ), 
    (
    "20130226", 
    "20130226", 
    "20130226", 
    ), 
    (
    "20130225", 
    "20130225" 
    )) 
+1

嘿!爲什麼downvotes?必須幫助人們。 Upvoting以抵消downvotes ... –

回答

2

您的代碼重複填充和清空同一陣列添加其元素,但您需要使用NSArray的其他實例來保留該結構。因此,請爲每個部分使用新的NSArray

for (int i=0; i<[DateSortArry2 count]; i++) { 
    NSMutableArray *section = [NSMutableArray array]; 
    for (int j=0; j<[DateSortArry2Copy count]; j++) { 
     NSString *sectiondateStr2 = [NSString stringWithFormat:@"%@",[DateSortArry2Copy objectAtIndex:j]];  
     if ([[DateSortArry2 objectAtIndex:i] isEqualToString:sectiondateStr2]) { 
      [section addObject:sectiondateStr2]; 
     } 
    } 
    [SumArry addObject:section]; 
} 
+0

非常感謝!sartak!你是對的! – SimonKira

2

您可以存儲到您的陣列中的另一個陣列(或任何類型的對象)的引用:

[myMutableArray addObject:otherArray]; 

或者concatinate陣列。

[myMutableArray addObjectsFromArray:otherArray]; 

這兩者都記錄在the documentation。從外觀上看,第一種方法是你想要的,因爲你想要有NSArrayNSMutableArray

1

試試這個: 請告訴我它是否有效。 謝謝

NSString *str = @""; 
    for (int i=0; i<[DateSortArry2 count]; i++) 
    { 
      if (str isEqualToString:[DateSortArry2 objectAtIndex:i]) 
      { 
       return; 
      } 
      else 
      { 
       NSMutableArray * Arry = [[NSMutableArray alloc] init]; 
       str = [DateSortArry2 objectAtIndex:i] 
       for (int j=0; j<[DateSortArry2Copy count]; j++) 
       { 
        if ([[DateSortArry2 objectAtIndex:i] isEqualToString:str]) 
        { 
         [Arry addObject:str]; 
        } 
       } 
       [SumArry addObject:Arry]; 
       [Arry removeAllObjects]; 
      } 
    }