2012-07-09 109 views
2

我有一個iPhone應用程序,我試圖添加兩個可變數組。如何結合兩個可變數組?

NSMutableArray *dataArray = [[NSMutableArray alloc] init]; 
NSMutableArray *dataArray1 = [[NSMutableArray alloc] init]; 
NSDictionary *news = [dict objectForKey:@"news"]; 
NSDictionary *deals = [dict objectForKey:@"deals"]; 
NSLog(@"%@", [news classForCoder]); 
NSLog(@"%@", news); 

for (NSDictionary *key in news) 
{ 
    if ([key isKindOfClass:[NSDictionary class]]) 
    { 
     [dataArray addObject:key];  
    } 
} 

for (NSDictionary *key in deals) 
{ 
    if ([key isKindOfClass:[NSDictionary class]]) 
    { 
     [dataArray1 addObject:key];   
    } 
} 

self.newssarray = dataArray; 
[self.mTableView reloadData]; 

在這裏,我要添加的兩個陣列「dataArray中」和「dataArray2」被合併成一個陣列(self.newsarray)。任何人都可以幫助我實現這個目標嗎?

回答

24

NSMutable陣列擁有所有的NSArray的方法,其中包括一個通過添加另一個陣列本身創建新陣列:

self.newsarray = [[dataArray arrayByAddingObjectsFromArray:dataArray1] mutableCopy]; 
+0

感謝您的回覆,但它給了我一個警告不兼容指針類型從nsmutable ar ray to nsarray? – hacker 2012-07-09 14:59:33

+0

我假設你的意思是@property預計是可變的;回答修改。 – 2012-07-09 15:05:39

+2

'self.newsarray = [[dataArray arrayByAddingObjectsFromArray:dataArray1] mutableCopy];'現在快樂.... – 2012-07-09 15:14:46

4

如果你的財產的NSMutableArray:

self.newsarray = [NSMutableArray arrayWithArray:[dataArray arrayByAddingObjectsFromArray:dataArray1]]; 

如果是的NSArray :

self.newsarray = [dataArray arrayByAddingObjectsFromArray:dataArray1];