2015-06-21 126 views
0

我有一个字符串------ NSString abc = @“apple:87,banana:32,grapes:54”;将NSString转换为NSDIctionary

我需要这个输出这样

{ 
    name = "apple"; 
    value = "87"; 
}, 
{ 
    name = "banana"; 
    value = "32"; 
}, 
{ 
    name = "grapes"; 
    value = "54"; 
} 

我曾尝试:

NSArray* itemList = [abc componentsSeparatedByString:@","]; 
NSMutableDictionary* dict = [NSMutableDictionary dictionary]; 

for (NSString* item in itemList) { 
    NSArray* subItemList = [item componentsSeparatedByString:@":"]; 

    if (subItemList.count > 0) { 
     [dict setObject:[subItemList objectAtIndex:1] forKey:[subItemList objectAtIndex:0]]; 
    } 
} 

NSLog(@"%@", dict); 

输出是 -

{ 
    apple = 87; 
    banana = 32; 
    grapes = 54; 
} 

,但我不希望这个输出

+0

的NSArray * itemList中= [ABC componentsSeparatedByString:@ “”]; NSMutableDictionary * dict = [NSMutableDictionary dictionary]; (itemListList)中的NSString * item { NSArray * subItemList = [item componentsSeparatedByString:@“:”];如果(subItemList.count> 0){[objectItem:[subItemList objectAtIndex:1] forKey:[subItemList objectAtIndex:0]]; } } NSLog(@“%@”,dict); 但我不想要这个输出---- – Eric

+0

请在问题中添加代码,而不是评论。你的代码看起来正是你想要的。但是你的标题描述了你想要作为字典的日志,而且我认为你真正的意思是你想要一个字典数组? – Wain

+0

我认为你需要更清楚你的问题。你不想要什么输出?你想要一个NSDictionary或者你想要一个像你写的第一个字符串(比如'='和';'而不是':'和','的JSON样式? – user1447414

回答

1

想要的输出是a NSArrayNSDictionary

所以:

NSArray* itemList = [abc componentsSeparatedByString:@","]; 
NSMutableArray *finalArray = [[NSMutableArray alloc] init]; 
for (NSString *aString in itemList) 
{ 
    NSArray* subItem = [aString componentsSeparatedByString:@":"]; 
    NSDictionary *dict = @{@"name":[subItem objectAtIndex:0], 
          @"value":[subItem objectAtIndex:1]}; 
    [finalArray addObject:dict]; 
} 

我没有使用if ([subItem count] > 0),努力只是为了让你错过了逻辑和澄清的算法。

我没有测试代码,但应该这样做。 (或者一个小编译器错误很容易纠正)。

+0

非常感谢:) - Larme – Eric

+0

'子项[0]'和'[1]'会更清晰,尽管答案已经非常好。 – Tommy

+0

@Tommy:我不想为'NSArray'('objectAtIndex:'等效)使用短手语法,因为已经对所需输出的结构感到困惑,只为'NSDictionary'项目保留简写语法。我认为这种简短的语法将可能已经被绑定的人与“我操纵什么对象?”混为一谈,但这是个人观点。 – Larme

1

如果有人想在夫特等效:

let abc = "apple:87,banana:32,grapes:54" 

let dict = abc.componentsSeparatedByString(",").map { pair -> [String: String] in 
    let parts = pair.componentsSeparatedByString(":") 
    return ["name": parts[0], "value": parts[1]] 
}