ios - 将数据传递给对象后,对象值返回 nil

标签 ios swift object

我正在尝试学习 MVVM 设计模式并编写简洁易读的代码。问题是我从将我的 json 响应对象映射到的对象中得到 nil 值。我已经检查了大部分我正在做的事情,但我仍然得到 nils。这是我的代码。

搜索对象:

class SearchResultObj: NSObject {

var status : Bool
var name: String?
var publicKey: String?
var profileImage: String?
var accountType: String?

init (model: SearchResultObj) {

    if let value = model.status as? Bool {
        self.status = value
    }else{
        self.status = false
    }
    if let fullname = model.name {
        self.name = fullname
    }else{
        self.name = nil
    }

    if let key = model.publicKey {
        self.publicKey = key
    }else{
        self.publicKey = nil
    }

    if let profimage = model.profileImage {
        self.profileImage = profimage
    }else{
        self.profileImage = nil
    }
    if let account = model.accountType {
        self.accountType = account
    }else{
        self.accountType = nil
    }
  }
}

View 模型

    func searchDataRequested(_ apiUrl: String,_ country: String,_ phone:String) {

        var search: SearchResultObj?

     init() {
          self.search = SearchResultObj()
      }


    let service = ServiceCall(urlServiceCall: apiUrl, country: country, phone: phone)
        let url = URL(string: apiUrl)
        let request = URLRequest(url: url!)
        let country = country
        let phone = phone


    service.fetchJson(request: request, customerCountry: country, mobileNumber: phone) // making service call and returns json
         { (ok, json) in
            print("CallBack response : \(String(describing: json))")

            self.jsonMappingToSearch(json! as AnyObject)
    }
}

func jsonMappingToSearch(_ json: AnyObject) {

    print( json["fullName"] as! String?) // This returns a value 
    search?.name = json["fullName"] as! String?
    search?.profileImage = json["image"] as! String?
    search?.publicKey = json["publicKey"] as! String?
    search?.accountType = json["accountType"] as! String?
    search?.status = (json["status"] as! Bool?)!
    testResponse()
}

func testResponse(){  

    // testing to see if my object contains anything
    print(search?.name as Any )
    print(search?.profileImage as Any )
    print(search?.publicKey as Any )
    print(search?.accountType as Any )
    print(search?.status as Any )
}

所以我在一个单独的类中进行服务调用,然后将完成处理程序中的响应传递给方法 self.jsonMappingToSearch(json! as AnyObject)。之后我想将响应映射到我的 SearchObject。当我打印出 json 对象的值时,我确实获得了实际值,但是在 map 函数运行后,我无法获得对象中的任何值,因为它返回所有 nils。

最佳答案

如果您真的在寻找干净、可读的代码,您应该查看 Codable Protocol在 Swift 4 中。这样,您的代码将变成如下所示,而不是具有大量手动 JSON 映射,并且应该处理 JSON 数据中的 nils):

class SearchResultObj: NSObject, Codable {

    var status = false
    var name: String?
    var publicKey: String?
    var profileImage: String?
    var accountType: String?

    enum CodingKeys: String, CodingKey {
        case status
        case name = "fullName"
        case publicKey
        case profileImage = "image"
        case accountType
    }
}

func searchDataRequested(_ apiUrl: String,_ country: String,_ phone:String) {

    let service = ServiceCall(urlServiceCall: apiUrl, country: country, phone: phone)
    let url = URL(string: apiUrl)
    let request = URLRequest(url: url!)
    let country = country
    let phone = phone

    service.fetchJson(request: request, customerCountry: country, mobileNumber: phone) // making service call and returns json
    { (ok, json) in
        print("CallBack response : \(String(describing: json))")

        //I'm assuming your JSON is just a Data representation of the JSON string here
        let decoder = JSONDecoder()
        let result = decoder.decode(SearchResultObj.self, from: json)

        //Add breakpoint or print to verify the result here
    }
}

如果您可以发布源 JSON,如果您仍然遇到问题,那也会有所帮助。

关于ios - 将数据传递给对象后,对象值返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49801954/

相关文章:

iphone - 在 iPhone 中,要支持蓝牙耳机,我需要做些什么吗?

ios - 如何在委托(delegate)中加载插页式广告并在另一个 View Controller 中显示?

ios - 键盘不隐藏有两个 UITextField 和一个调用选择器的

ios/swift - 如何禁用键盘?

c++ - 如何根据 C++ 标准访问对象表示?

ios - 未收到NSNotification

swift - 如何合并来自循环的多个单独的 json 结果然后返回 swift

ios - 检查电池电量 iOS Swift

objective-c - NSArray 循环抓取对象

javascript - 将过滤功能与 map 相结合