Observer patterns for iOS design patterns and mechanisms

Source: Internet
Author: User

The Observer pattern defines a one-to-many dependency that allows multiple observer objects to listen to a Subject object at the same time. When the subject object changes in state, all observer objects are notified so that they can automatically update themselves.

The idea of the Observer pattern: When an object changes, the observer automatically notifies all relevant states to update

Observer pattern implementations in iOS: There are four ways to Nsnotification, KVO, Protocol, and code block blocks

Focus:

*notification is a one-to-many, and the delegate callback is one-to

The *notification-notificationcenter mechanism uses the inter-object communication function of the operating system, while delegate is a direct function call. The notification span is large, while the delegate efficiency may be higher.

* Compared to the former two KVO is a real observer pattern, he allows you to bind a handler function to a class's properties, the property will be automatically triggered when changes occur, unlike the others need you to manually send notifications. KVO is a flexible observation mechanism, which is widely used in interface design.

*code Bolock is actually equivalent to the C function pointer, can be used to do various callbacks. I think it should have the highest efficiency. One thing to note about using code block is the use of external variables. Referencing an external variable directly in the block will copy a copy of the external variable at the time the block is defined, that is, the value of the block definition, and the change of the value within the block will not be passed to the outside. To get real-time data, or to pass the data out, you need to add __block to the relevant variable.

Observer patterns for iOS design patterns and mechanisms

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.