IOS 10 objectForKey(“key”)的兼容性

时间:2016-09-08 15:39:48

标签: ios swift ios10

我正在处理我的应用程序与IOS10的兼容性,我在执行此代码时遇到问题:

if let results = NSJSONSerialization.TryJSONObjectWithData(data, options: []) as? NSDictionary {
    print(" results : \(results)");

    if let networkPosts = results["results"] as? NSMutableArray {
        print(" here");

                for i in 0 ..< networkPosts.count {
                    let post:Post = Post(postDictionary: networkPosts[i] as! NSDictionary, context: (UIApplication.sharedApplication().delegate as! 

AppDelegate).coreDataHelper.managedObjectContext);
}
        }
    }

我可以看到结果,所以JSON没问题,但是在我看不到字典的结果键之后。 “这里”永远不会打印在我的控制台上。我试着制作一个断点,同样它不会通过那里。 我也尝试使用.objectForKey("key")但结果相同:/

有人能帮助我吗?

如果我使用results["results"] as? [[String: Any]]

然后

  

networkPosts [i] as! NSDictionary总是失败

1 个答案:

答案 0 :(得分:1)

在使用TryJSONObjectWithData使数组和字典可变时,您应该使用NSJSONReadingMutableContainers选项

https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/#//apple_ref/c/tdef/NSJSONReadingOptions

使用Playground for Swift 3测试的示例:

let jsonString = "{\"name\":\"Mattia\",\"iosDevices\":[\"iPhone6\",\"iPad Air 2\",\"iPhone6+\"]} 
let jsonData = jsonString.data(using: String.Encoding.utf8, allowLossyConversion: false)!

if let results = try JSONSerialization.jsonObject(with: jsonData, options: [.mutableContainers]) as? NSDictionary {
    print(" results : \(results)");

    if let networkPosts = results["iosDevices"] as? NSMutableArray {
        print(" here");
    }
}