2014-01-16 181 views
1

我有一個數組包含在其中的每個索引數組。如何從NSArray中刪除括號?

array is :(
     (
     "http://localhost/ColorPicker/upload/2014-01-14-04-01-19g1.jpg", 
     "http://localhost/ColorPicker/upload/2014-01-14-04-01-20g2.jpg", 
     "http://localhost/ColorPicker/upload/2014-01-14-04-01-20g3.jpg" 
    ), 
     (
     "http://localhost/ColorPicker/upload/2014-01-14-04-01-49y1.jpg", 
     "http://localhost/ColorPicker/upload/2014-01-14-04-01-50y2.jpg" 
    ), 
     (
     "http://localhost/ColorPicker/upload/2014-01-14-04-01-50y3.jpg", 
     "http://localhost/ColorPicker/upload/2014-01-14-04-01-51y6.jpg" 

    ) 
) 

我想做出一個單個陣列等

( 
"http://localhost/ColorPicker/upload/2014-01-14-04-01-50y3.jpg", 
"http://localhost/ColorPicker/upload/2014-01-14-04-01-51y6.jpg", 
"http://localhost/ColorPicker/upload/2014-01-14-04-01-50y3.jpg", 
"http://localhost/ColorPicker/upload/2014-01-14-04-01-51y6.jpg",      
"http://localhost/ColorPicker/upload/2014-01-14-04-01-50y3.jpg", 
"http://localhost/ColorPicker/upload/2014-01-14-04-01-51y6.jpg" 
    ) 
陣列內

怎樣消除(),(),並含有URL的單個陣列。

+4

那些字符不*在數組中 - 它們在那裏幫助你瞭解轉儲。在這種情況下,您有包含3個其他數組的數組轉儲。 –

+1

@HotLicks,我想OP知道。他問的是如何從嵌套數組中創建一個新的平面數組。 –

回答

2

你必須規範你的陣列 通過陣列循環,然後它所有的子陣列,並將它們添加到另一個陣列 這樣的事情應該足以讓你開始:here

8

你需要做一個新的數組:

NSMutableArray *newArray = [[NSMutableArray alloc] init]; 
for (NSArray *a in array) 
    [newArray addObjectsFromArray:a]; 
+0

不錯,一個深度嵌套數組! – zaph

+0

哦,我忘了addObjectsFromArray。做得好。比我的代碼簡單。 –

3

你需要編寫代碼來走你的外部陣列,複製第二級陣列的內容爲「平」陣列。事情是這樣的:

-(NSArray)flattenArray: (NSArray *) sourceArray; 
{ 
    NSMutableArray *result = [[NSMutableArray alloc] init]; 
    for (NSArray *array sourceArray) 
    { 
    //Make sure this object is an array of some kind. 
    //(use isKindOFClass to handle different types of array class cluster) 
    if ([array isKindOfClass: [NSArray class]) 
    { 
    [result addObjectsFromArray: array]; 
    } 
    else 
    { 
    NSLog(@"Non-array object %@ found. Adding directly.", array); 
    [result addObject: array]; 
    } 
    return [result copy]; //return an immutable copy of the result array 
} 
+0

這悄悄地從原始數組中刪除任何非數組成員,這是令人困惑的。意外結構的崩潰是可以的,但安靜地忽略它是危險的。也沒有理由返回副本。直接返回NSMutableArray沒有任何問題。 –

+0

我有一個數組中的每個索引都有另一個數組。 – Exception

+0

@Rob Napier,我可以很容易地決定將非數組對象添加到扁平數組中。這種具體的錯誤處理決定取決於應用程序的需求。對於論壇帖子,我傾向於僅僅回答問題的最低限度,並且將所有邊緣案例檢查留下充實的方法作爲OP的練習。 –

6

您可以使用鍵 - 值編碼人員 「@unionOfArrays」 扁平化的陣列(基於卡爾Norum時的帖子使用addObjectsFromArray編輯):

NSArray *nested = @[@[@"A1", @"A2", @"A3"], @[@"B1", @"B2", @"B3"], @[@"C1", @"C2", @"C3"]]; 
NSArray *flattened = [nested valueForKeyPath:@"@unionOfArrays.self"]; 

NSLog(@"nested = %@", nested); 
NSLog(@"flattened = %@", flattened); 

輸出:

 
nested = (
     (
     A1, 
     A2, 
     A3 
    ), 
     (
     B1, 
     B2, 
     B3 
    ), 
     (
     C1, 
     C2, 
     C3 
    ) 
) 
flattened = (
    A1, 
    A2, 
    A3, 
    B1, 
    B2, 
    B3, 
    C1, 
    C2, 
    C3 
) 
+0

哦!是的KVC rockss提供了強大的解決方案:)我很喜歡它。 +1 – Tirth