Search code examples
iosobjective-cnsstringnsarray

Unable to convert comma separated string to an array


I am using the following code to convert a comma separated string to an array.

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

NSLog(@"%@",domanIdStr); prints

(
    "1,2"
)

But then the third line componentsSeparatedByString throws the following error,

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

How can I be able to sort this out ?


Solution

  • NSLog(@"%@",domanIdStr); prints

    (
        "1,2"
    )
    

    domanIdStr is not a string, it is an array. So, to properly get the domanIdStr, use this

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

    or else if you want to extract then do like

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