如何在iOS中将字符串转换为数组?

时间:2016-11-21 12:41:20

标签: ios objective-c

NSString *strdetails = [NSString stringWithFormat:@"%@",[[products objectAtIndex:i] valueForKey:@"details"]];

NSLog(@"%@",strdetails);

当我添加数组但它转换为以前的数据时。但我希望数组不是字符串。

3 个答案:

答案 0 :(得分:2)

这是你的代码:

NSString *strdetails = [NSString stringWithFormat:@"%@",[[products objectAtIndex:i] valueForKey:@"details"]];

NSLog(@"%@",strdetails);

我在这里更新此代码:

NSData *objectData = [strdetails dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:objectData
                                      options:NSJSONReadingMutableContainers 
                                        error:&jsonError];

 // Here you are getting dictionary, Now from this you will get array in this way
    // Print this dict
    NSLog(@"dict details =  %@",dict);
        NSArray * arrV = dict[@"variants"];
    // check your array

答案 1 :(得分:0)

我猜你正在将jsonString转换为数组我正在使用下面的函数来转换我的jsonString。

<强>的ViewController

public class func JSONParseArray(jsonString: NSString) -> [AnyObject]?{

if let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding){

if let array = (try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)))  as? [AnyObject] {
            return array
         }
    }
    return nil    
 }

如果您想从数组中获取特定值:

NSArray *outputArray = [array valueForKey:@"YourKey"];

答案 2 :(得分:0)

NSString *str=@"Hi,I LOVE IOS"; 
NSArray *arr = [str componentsSeparatedByString:@","];
NSString *strSecond = [arr objectAtIndex:1];

NSMutableArray *arrIOS = [strSecond componentsSeparatedByString:@" "];
NSString *strI = [arrIOS objectAtIndex:0];
NSString *strLOVE = [arrIOS objectAtIndex:1];
NSString *strIOS = [arrIOS objectAtIndex:2];

[arr removeObjectAtIndex:1];
[arr addObject:@","];
[arr addObject:strI];
[arr addObject:strLOVE];
[arr addObject:strIOS];