Use of iOS swift4 KVO

Source: Internet
Author: User

Before SWIFT4, using KVO only needs to inherit nsobject. However, after the SWIFT4 has changed, you must add the @objcmembers modifier before class, otherwise there will be no effect.

Here's an example: if you define a person class that wants to listen to its KVO changes in addition to inheriting nsobject, you must also add the @objcmembers modifier before class, otherwise it will not work.

@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) {

}

}

This is used to validate the JSON-to-model for convenience.

Class Viewcontroller:uiviewcontroller {

Override Func Viewdidload () {

Super.viewdidload ()

Let JSON = [' name ': ' Zhang San ', ' age ': ' 20 ']

Let p = person (Dic:json)

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

}

Override Func didreceivememorywarning () {

Super.didreceivememorywarning ()

Dispose of any resources the can be recreated.

}

}

The result is output:----->>Optional (" Zhang San "), if you remove @objcmembers this modifier will not work, the result is output:----- >> Nil.

So in the SWIFT4 to use KVO must add @objcmembers otherwise it will not work.

If the project uses this kind of KVO to do the JSON to the model, you need to make the appropriate adjustments, because for today encountered this problem, resolved after the record, so that you or others to learn the reference.

Jane Book Address: Code Life

Use of iOS swift4 KVO

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.