gpt4 book ai didi

ios - [iOS][objC] 无法将 NSDictionary 中的值转换为 NSString

转载 作者:行者123 更新时间:2023-11-29 04:42:13 26 4
gpt4 key购买 nike

我打算将 iOS SDK 中的 NSDictionary* 对象转换为 NSString*。

假设我的 NSDictionary 对象具有以下键值对:{"aps":{"badge":9, "alert":"hello"}} (注意 value 本身是一个 NSDictionary 对象)我希望它转换成一个 HashMap ,其键值对为 {"aps":"badge:9,alert:hello"} (注意值只是一个字符串)。

我可以使用以下代码打印 NsDictionary 中的值:

NSDictionary *userInfo; //it is passed as an argument and contains the string I mentioned above
for (id key in userInfo)
{
NSString* value = [userInfo valueForKey:key];
funct( [value UTF9String]; // my function
}

但是我无法在像 UTT8String 这样的值对象上调用任何 NSString 方法。它给我错误“由于未捕获的异常 NSInvalidArgumentException 而终止应用程序:原因 [_NSCFDictionary UTF8String]:发送到实例的无法识别的选择器

最佳答案

您将必须递归地处理字典结构,这是您应该能够适应的示例:

-(void)processParsedObject:(id)object{
[self processParsedObject:object depth:0 parent:nil];
}

-(void)processParsedObject:(id)object depth:(int)depth parent:(id)parent{

if([object isKindOfClass:[NSDictionary class]]){

for(NSString * key in [object allKeys]){
id child = [object objectForKey:key];
[self processParsedObject:child depth:depth+1 parent:object];
}


}else if([object isKindOfClass:[NSArray class]]){

for(id child in object){
[self processParsedObject:child depth:depth+1 parent:object];
}

}
else{
//This object is not a container you might be interested in it's value
NSLog(@"Node: %@ depth: %d",[object description],depth);
}


}

关于ios - [iOS][objC] 无法将 NSDictionary 中的值转换为 NSString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10222360/

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