How to convert elements of NSMutableArray to NSStr

2020-04-16 18:53发布

I have 1 NSMutableArray and I want to convert whatever data in array will be in NSString. tell me code for that. Array is nothing but object of NSMutableArray class.

标签: iphone cocoa
3条回答
虎瘦雄心在
2楼-- · 2020-04-16 19:14

It depends on how do you want to use that string.

One way to convert an object to a string is to call -description (or -descriptionWithLocale:) on that object. For NSArray (or NSMutableArray) -description method returns a string that represents the contents of the receiver, formatted as a property list. The result you'll get will also depend on how -description method implemented in objects in array.

查看更多
劫难
3楼-- · 2020-04-16 19:26

If you want only the elements of array then you can try componentsJoinedByString:. This method returns all the elements with separator string without other formatting info.

[array componentsJoinedByString:@","];

Here "," is separator string.

查看更多
够拽才男人
4楼-- · 2020-04-16 19:33

It depends on how you want your string. One approach could be iterate through array and convert each element of it.

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

You can modify the above code based on item's class.

Below code will convert Array to string with commas and other information.

NSString * result = [array description];
查看更多
登录 后发表回答