setValuesForKeys函数抛出错误?

时间:2017-10-18 19:18:45

标签: swift swift3 swift4 setvalue swift-dictionary

我有一个json文件链接在这里JSON

我想要做的是" setValuesForKeys"在我的appCatagory类中,它会抛出一个错误:"由于未捕获的异常终止应用程序' NSUnknownKeyException',原因:' [setValue:forUndefinedKey:]:此类不是键值编码 - 符合密钥类型。"

我在appCatagory类中获得了所有必需的属性,并且Json输出也正确但我无法设置键的值。请帮助:

import UIKit

class AppCategory:NSObject{

var name:String?
var apps:[App]?
var type:String?



override func setValue(_ value: Any?, forKey key: String) {
        //this if statement below isn't run even though i fetch apps key
    if key == "apps" {
        apps = [App]()
        for dict in value as! [[String: AnyObject]] {
            let app = App()
            app.setValuesForKeys(dict)
            apps?.append(app)
        }

    } else {

        super.setValue(value, forKey: key)
    }
}


static func fetchFeaturedApps(){
    let urlString = "https://api.letsbuildthatapp.com/appstore/featured"
URLSession.shared.dataTask(with: URL(string:urlString)!) { (data, response, error)-> Void in

    if error != nil{

        print(error!)
        return

    }
    do{
        let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String:Any]


        var appCategories = [AppCategory]()
        for dict in (json!["categories"] as? [[String:Any]])! {
            let appCategory = AppCategory()

           appCategory.setValuesForKeys(dict)
           appCategories.append(appCategory)
        }
        DispatchQueue.main.async(execute: { () -> Void in
            completionHandler(appCategories)
        })
    }catch let err{
        print(err)
    }

    }.resume()
}

static func sampleAppCategories() ->[AppCategory]{

let bestNewAppsCategory = AppCategory()
 bestNewAppsCategory.name = "Best New Apps"

    var apps = [App]()

    let frozenApp = App()
    frozenApp.name = "Disney Build It : Frozen"
    frozenApp.imageName = "Frozen"
    frozenApp.category = "Entertainment"
    frozenApp.price = NSNumber(value: 3.99)
    apps.append(frozenApp)
    bestNewAppsCategory.apps = apps

 //Create a new category and name
    let bestNewGamesCategory = AppCategory()
    bestNewGamesCategory.name = "Best New Games"
    var bestNewGamesApps = [App]()

    let telepaintApp = App()
    telepaintApp.name = "Telepaint"
    telepaintApp.category = "Games"
    telepaintApp.imageName = "Telepaint"

    telepaintApp.price = NSNumber(value: 2.99)
    bestNewGamesApps.append(telepaintApp)
    bestNewGamesCategory.apps = bestNewGamesApps

    return [bestNewAppsCategory , bestNewGamesCategory]
}
}

class App: NSObject {

  var id: NSNumber?
   var name: String?
   var category: String?
var imageName:String?
  var price: NSNumber?

0 个答案:

没有答案