无法将逗号分隔的字符串转换为数组

时间:2017-05-19 12:23:59

标签: ios objective-c nsstring nsarray

我使用以下代码将逗号分隔的字符串转换为数组。

NSString *domanIdStr = [Settings getSetting:@"selectedDomainId"];
NSLog(@"%@",domanIdStr);
NSArray *domainIds = [domanIdStr componentsSeparatedByString:@","];

NSLog(@"%@",domanIdStr);打印

(
    "1,2"
)

但是第三行componentsSeparatedByString会引发以下错误,

[__NSCFArray componentsSeparatedByString:]: unrecognized selector sent to instance 0x1702650c0

我怎样才能解决这个问题?

3 个答案:

答案 0 :(得分:2)

NSLog(@"%@",domanIdStr);打印

(
    "1,2"
)

domanIdStr不是字符串,而是数组。因此,要正确获取domanIdStr,请使用此

NSArray * domanIdStr = [Settings getSetting:@"selectedDomainId"];
NSString *firstTag = domanIdStr[0]; //this would be "1"

或者如果你想提取,那么就像

一样
 NSArray *domanIdStr = [Settings getSetting:@"selectedDomainId"];
 NSString *getString = domanIdStr[0];
NSArray *domainIds = [getString componentsSeparatedByString:@","];
NSLog(@"%@",domanIdStr[0]);

答案 1 :(得分:1)

使用以下

替换您的代码
NSArray *domanIdStr = [Settings getSetting:@"selectedDomainId"];
NSString *str = domanIdStr[0];
NSArray *domainIds = [str componentsSeparatedByString:@","];

答案 2 :(得分:0)

你正在获取关键字selectedDomainId的数组,如果你得到一个字符串,那么问题将被解决。