Convert NSArray to NSString in Objective-C

后端 未结 9 1289
难免孤独
难免孤独 2020-11-28 01:13

I am wondering how to convert an NSArray [@\"Apple\", @\"Pear \", 323, @\"Orange\"] to a string in Objective-C.

9条回答
  •  暖寄归人
    2020-11-28 01:30

    One approach would be to iterate over the array, calling the description message on each item:

    NSMutableString * result = [[NSMutableString alloc] init];
    for (NSObject * obj in array)
    {
        [result appendString:[obj description]];
    }
    NSLog(@"The concatenated string is %@", result);
    

    Another approach would be to do something based on each item's class:

    NSMutableString * result = [[NSMutableString alloc] init];
    for (NSObject * obj in array)
    {
        if ([obj isKindOfClass:[NSNumber class]])
        {
            // append something
        }
        else
        {
            [result appendString:[obj description]];
        }
    }
    NSLog(@"The concatenated string is %@", result);
    

    If you want commas and other extraneous information, you can just do:

    NSString * result = [array description];
    

提交回复
热议问题