2015-04-23 38 views
0

我有一個名爲child_list的數組,如child_list:「9,8,21,22,20,24,25」,在索引0時將它轉換爲NSString,當我將它轉換爲字符串時,它的工作,但是當我使用NSMutableArray時,它崩潰,我不知道爲什麼。iOS如何以逗號分隔的數組對象轉換爲字符串?

我的代碼是在這裏:

if([theDictionary objectForKey:@"child_list"]) 
    { 
     NSString *str = [[theDictionary objectForKey:@"child_list"]objectAtIndex:0]; 
     NSLog(@"Child List %@",str); 
     _child_list = [[NSMutableArray alloc ]initWithObjects: [str componentsSeparatedByString:@","], nil]; 
    } 

當破發點來吧str它顯示的結果,當談到對_child_list墜毀。

+0

做的NSLog(@ 「兒童名單%@」,STR);這個日誌打印「9」。或者只是「9」 – Vaisakh

+0

將child_list創建爲NSMutableArray。它會完美地工作。不需要改變任何東西。 –

+0

如何嘗試這樣做:_child_list = [str componentsSeparatedByString:@「,」]。mutableCopy –

回答

0

請分享您的日誌返回和您使用的字典.. 代碼[str componentsSeparatedByString:@","]返回一個數組。所以,當你分配一個可變數組時,你正在創建一個數組數組...而是使用initWithObjects,使用initWithArray方法並將[str componentsSeparatedByString:@","]傳遞給它。

+0

like that _child_list = [[NSMutableArray alloc] initWithArray:[str componentsSeparatedByString:@「,」],nil]; – riz

+0

其錯誤 – riz

+0

不,用這種方式.. _child_list = [[NSMutableArray alloc] initWithArray:[str componentsSeparatedByString:@「,」]]; – Tejvansh

1

使用initWithArray而分配_child_list的NSMutableArray

方法
if([theDictionary objectForKey:@"child_list"]) 
    { 
     NSString *str = [[theDictionary objectForKey:@"child_list"]objectAtIndex:0]; 
     NSLog(@"Child List %@",str); 
     _child_list = [[NSMutableArray alloc ] initWithArray:[str componentsSeparatedByString:@","]]; 
    } 
+2

到底是什麼',nil'? 'arrayWithArray:'只有一個參數。而我不是簡單地在數組上使用'mutableCopy'? – rmaddy

+0

@bhavesh將arraywitharray當作你的代碼發生錯誤 – riz

相關問題