gpt4 book ai didi

swift - JSON 结果 (NSArray) : valueForKey doesn't work as expected

转载 作者:可可西里 更新时间:2023-11-01 00:53:56 28 4
gpt4 key购买 nike

作为 Web 服务 (JSON) 请求的结果,我有一个 NSArray。

如果我打印 NSLog("%@", jsonResult) 它正确显示的数组:

(
{
text = “Some text”;
coordinates = “11.333345 - 09.33349”;
}

{
text = “Some text2”;
coordinates = “11.333345 - 09.33349”;
}

{
text = “Some text3”;
coordinates = “11.333345 - 09.33349”;
}


)

但是如果我尝试使用以下函数访问 NSArray 中每个条目的键“文本”的值,我总是会得到如下输出:

Text )r'ì• (instead of "Some text2, 3 ....")

所以我认为是类型不匹配,但我不知道如何找出问题所在。在 Objective-C 中它工作得很好。

func getResult(){
self.webService.getResult({ jsonResult in

jsonResult!.enumerateObjectsUsingBlock({ object, index, stop in
var txt : NSString = object.valueForKey("text") as NSString
NSLog("Text %s", txt)

})

NSLog("Ready %@", jsonResult!)

});
}

知道出了什么问题吗?

更新 1

我发现,如果我只使用 NSObject 而不是 NSString,它会正确显示文本

var txt : NSObject = object.valueForKey("text") as NSObject
NSLog("%@", txt)

但无论如何,我必须将该 NSObject 对象转换为 NSString 或 String,以显示...

它期望使用哪种编码来显示字符串...或者如何转换此 NSObject????

最佳答案

var txt : NSString = object.valueForKey("text") as NSString
NSLog("Text %s", txt)

问题是 %s 格式说明符,它用于 C 风格的字符串。您需要 %@,它用于对象。

在 Swift 中,推荐使用 println(),它完全消除了格式字符串:

var txt : NSString = object.valueForKey("text") as NSString
println("Text \(txt)")

关于swift - JSON 结果 (NSArray) : valueForKey doesn't work as expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24042771/

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