Using runtime and AOP to realize KVO in OC

Source: Internet
Author: User

The KVO Observer pattern realized in OC is rather stiff, does not support block, and realizes it by using runtime mechanism.

Detailed implementation steps:

One: Add a category to the NSObject (add the appropriate observer, delete the Observer's method), so that all inherited NSObject class generated objects will have these two methods.

Second: In the method of adding observers, check whether this class has attributes that the observer wants to observe. If so, proceed to the next step.

Third: Check whether the set method of this property of the object has been replaced by the method implementation, if there is no next step, if there are fifth steps.

Four: The implementation of this property's set method points to the AOP method, and adds a corresponding method to the implementation of the original set method.

Five: The Observer (which can be an object that encapsulates the properties of an observer, I just encapsulated an additional class) into my own dictionary (I use a dictionary or other model).

Six: Write the AOP method, the AOP method implements the call to the original set method, and implements the broadcast to the Observer. (The call order of two methods can be customized, which is AOP pre-and post-cut)

Tips:  

The above is just a simple process step, message to provide source code, welcome to discuss the study together.

Using runtime and AOP to realize KVO in OC

Related Article

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.