【问题标题】:Trying to create an object with Json data尝试使用 Json 数据创建对象
【发布时间】:2015-10-16 03:18:05
【问题描述】:

我正在学习 Swift 并为大学创建一个小应用程序。我正在使用 Alamofire 和 SwiftyJSON 来处理我的 API。

模型产品

class Products {
    var id: Int {
        get {
            return self.id
        }
        set {
            self.id = newValue
        }
    }

    var name: String {
        get {
            return self.name
        }
        set {
            self.name = newValue
        }
    }

    var description: String {
        get {
            return self.description
        }
        set {
            self.description = newValue
        }
    }

    var price: String {
        get {
            return self.price
        }
        set {
            self.price = newValue
        }
    }

    init(id: Int, name: String, description: String, price: String) {
        self.id = id
        self.name = name
        self.description = description
        self.price = price
    }
}

我的视图控制器

import UIKit
import Alamofire
import SwiftyJSON

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        Alamofire.request(.GET, Urls.menu).responseJSON { request in
            if let json = request.result.value {
                let data = JSON(json)

                for (_, subJson): (String, JSON) in data {
                    let product = Products(id: subJson["id"].int!, name: subJson["name"].string!, description: subJson["description"].string!, price: subJson["price"].string!)
                }
            }
        }
    }
}

当我尝试运行我的代码时,我在我的模型产品第 14 行收到一个错误:

线程 1:EX_BAD_ACCESS(代码=2,地址=0x7fff5e961ff8)

在我的属性 id 的设置器中。

我在 xcode 中查看了我的错误日志,它显示这个 setter 被调用了超过 25 万次。

谁能知道我做错了什么?

谢谢。

【问题讨论】:

    标签: ios json swift swifty-json


    【解决方案1】:

    您的代码会导致无限循环,因为显式 setter 一次又一次地调用自己。

    在 Swift 中,属性是隐式合成的,只需声明它们就足够了。

    class Products {
        var id: Int 
        var name: String
        var description: String 
        var price: String 
    
        init(id: Int, name: String, description: String, price: String) {
            self.id = id
            self.name = name
            self.description = description
            self.price = price
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-01
      • 2016-01-11
      • 2020-07-10
      • 1970-01-01
      • 1970-01-01
      • 2012-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多