Convert NSArray to NSString in Objective-C

后端 未结 9 1211
难免孤独
难免孤独 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:21

    Swift 3.0 solution:

    let string = array.joined(separator: " ")
    
    0 讨论(0)
  • 2020-11-28 01:22

    The way I know is easy.

    var NSArray_variable = NSArray_Object[n]
    var stringVarible = NSArray_variable as String
    

    n is the inner position in the array This in SWIFT Language. It might work in Objective C

    0 讨论(0)
  • 2020-11-28 01:27
    NSArray *array = [NSArray arrayWithObjects:@"One",@"Two",@"Three", nil];
    NSString *stringFromArray = [array componentsJoinedByString:@" "];
    

    The first line initializes an array with objects. The second line joins all elements of that array by adding the string inside the "" and returns a string.

    0 讨论(0)
  • 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];
    
    0 讨论(0)
  • 2020-11-28 01:31
    NSString * str = [componentsJoinedByString:@""];
    

    and you have dic or multiple array then used bellow

    NSString * result = [[array valueForKey:@"description"] componentsJoinedByString:@""];   
    
    0 讨论(0)
  • 2020-11-28 01:32
    NSString * result = [[array valueForKey:@"description"] componentsJoinedByString:@""];
    
    0 讨论(0)
提交回复
热议问题