gpt4 book ai didi

ios - 将 NSString 转换为 NSDIctionary

转载 作者:行者123 更新时间:2023-11-28 21:44:09 28 4
gpt4 key购买 nike

我有一个字符串 ------ NSString abc = @"apple:87,banana:32,grapes:54";

我需要这样的输出

{
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;
}

但我不想要这个输出

最佳答案

想要的输出是 NSDictionaryNSArray

所以:

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),只是想保持您错过的逻辑并阐明算法。

我没有测试代码,但应该可以。 (或者可能是一些容易纠正的编译器错误)。

关于ios - 将 NSString 转换为 NSDIctionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30968639/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com