ios swift4之kvo的使用

來源:互聯網
上載者:User

標籤:fan   sel   ide   let   var   UI   ted   www.   string   

在swift4之前,使用kvo只需要繼承NSObject 就可以了。但是swift4之後發生了變化,必須在class之前加入@objcMembers修飾,不然就沒有效果了。

下面舉個例子:如定義一個Person類想監聽其kvo的變化除了繼承NSObject之外,還必須在class之前添加@objcMembers這個修飾符,不然沒有效果。

@objcMembers class Person: NSObject {

 var name:String?

 var age:Int=0

override init() {

 super.init()

    }

 

 init(dic:[String:Any]) {

 

 super.init()

 

 self.setValuesForKeys(dic)

    }

 

 override func setValue(_ value: Any?, forUndefinedKey key: String) {

 

    }

}

這裡為了方便就使用它來進行json轉模型進行驗證

 

class ViewController: UIViewController {

 

 override func viewDidLoad() {

 super.viewDidLoad()

 let json = ["name":"張三","age":"20"]

 let p = Person(dic:json)

 print("----->>",p.name)

    }

 override func didReceiveMemoryWarning() {

 super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

}

 

結果就輸出了:----->>Optional("張三"),如果去掉@objcMembers這個修飾符就不起作用了,結果就輸出:----->> nil。

所以在swift4中要用kvo就必須加@objcMembers否則就不起作用了。

如果項目中用到了這種kvo自己做json轉模型的話就需要做相應的調整了,因為為今天遇到了這個問題,解決了之後記錄下來,以便自己或他人學習參考。

 

簡書地址:Code人生

ios swift4之kvo的使用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.