IOS fun talk design model-notification, ios fun talk Design Model

Source: Internet
Author: User
Tags notification center

IOS fun talk design model-notification, ios fun talk Design Model

[Preface]

A design mode of iOS, the Observer mode (also called publish/Subscribe, namely Publich/Subscribe mode ).

Observer mode, which includes notification and KVO (Key-value-observing) mechanisms.

In this article, we will introduce the frequently usedNotification MechanismThis design pattern.

 

Notification Mechanism

The delegation mechanism refers to communication between "one-to-one" objects, while the notification mechanism refers to communication between "one-to-many" objects;

 

1. What is it? [Examples of life problems]

"Text message Weather Forecast"

When Class A sends A message to the notification center, group B registered as A user (observer) will receive the corresponding notification and respond accordingly.

 

2. What is the purpose? [Application in code]

How do I transmit data between different classes?

There are several methods: property transfer, proxy protocol, and notification.

Notification: The method created in Class A and executed in Class B. You can use this notification to transmit data to the other party;

 

3. What is the difference? [Different from other "notifications ?]

Frequently-mentioned notifications include "broadcast notification", "local notification", and "push notification"

This article introduces broadcast notification, which is a mechanism for implementing the observer mode. It can communicate with multiple objects in an application to transmit data.

Local notifications and push notifications mainly send "Notification prompts" to users, such as warning prompts, sound, vibrations, and marked red numbers.

The first is to send a local notification to the user, the second is to send a third-party application to Apple's official remote server, and then the server "pushes the notification" to the user.

 

4. Product Manager: Old Rules, use the code ~ [Specific implementation]

Process:

  • In the notification mechanism, all objects that need (or are interested) to receive a notification can become the receiver. First, they register as the observer.
  • After registration, the notification center broadcasts the notification information sent by the publisher to the observer who has registered the notification. In addition, the observer can only receive information from the notification center and cannot know who delivered the notification.
  • Finally, when the recipient does not want to care about the notification, he or she can cancel the registration in the notification center and no longer receive the notification.

1. Get the notification center object (just like getting the permission of the mobile operator's SMS center as a media)

Release, registration, and release notifications are all requiredNotification centerTo facilitate message communication between different objects and classes.

[Nsicationicationcenter defacenter center]; // The notification center is also a singleton.

 

2. Publish (Class A) and receive (Class B)

A. send notifications as the publisher's class:

You can use the following three methods:

- (void)postNotification:(NSNotification *)notification;- (void)postNotificationName:(NSString *)aName object:(id)anObject;- (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;
  • Posticationicationname: Specifies the message name;
  • Object: Specifies the sender;
  • UserInfo: the carrier used to pass Parameters in the notification. The parameter is placed in userInfo of the NSDictionary type. For example, NSDictionary * dict = [notification userInfo];

The third method is generally used. If the parameter is not required, it can be set to nil.

B. register the notification and add it to the observer:

Register the notification as the observer Class B for listening:

- (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSString *)aName object:(nullable id)anObject;
// @ Selector is the callback method. In this class, notifications are processed accordingly. The name is the notification name and the object is the object;

Analysis:

  • Object = nil, then the customer object (self) will receive the NSWindowDidBecomeMainNotification notification message from any object;
  • Name = nil, then the observer will receive all the messages of the object, but cannot determine the order of receiving these messages.
  • Object = nil, name = nil, the observer will receive all messages of all objects.

For an arbitrary observer, if the corresponding selector cannot have a custom method (for example, MyMethod) of this class, you can use [observer respondsToSelector: @ selector (MyMethod.

Therefore, the complete process of adding an observer is as follows:

if([observer respondsToSelector:@selector(MyMethod:)]) {        [[NSNotificationCenter defaultCenter] addObserver:observer selector:@selector(MyMethod:) name:NSWindowDidBecomeMainNotification object:nil];    }  

Of course, there is another way to register an observer in the Apple API:

- (id <NSObject>)addObserverForName:(nullable NSString *)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block

This method supports block callback in this method, while the queue parameter indicates that this module is performed in the queue.

However, this method is generally not used. Therefore, we recommend that you use the first method to create an observer.

C. Remove notification

Because the notification center does not retain the observer object, the registered object must be canceled before it is released. If this is not the case, when the notification appears again, the notification center sends messages to released observer objects, causing application crash.

In ARC, the system automatically recycles useless notification object memory. However, due to the delay of the system recycle mechanism, it is recommended that you develop a habit even if no error occurs, manually release useless notifications.

There are two ways to remove:

// Release all notifications
-(Void) removeObserver :( id) observer;
// Release the notification named aName-(void) removeObserver :( id) observer name :( nullable NSString *) aName object :( nullable id) anObject;

Generally, in the View Controller, you can send a release message in "didReceiveMemoryWarning:

-(Void) didReceiveMemoryWarning {[super didreceivemorywarning]; // remove the observer [[nsicationicationcenter defacenter center] removeObserver: self];}

 

5. Names of system notifications we used in those years ~

The system also comes with many useful notifications. We only need to register as the corresponding notification recipient, and the corresponding data changes can occur according to the changes in the notification Status.

Some system notifications are named as follows:

UIApplicationDidFinishLaunchingNotification // after the application is started, UIApplicationDidBecomActiveNotification // enter the foreground UIApplicationWillResignActiveNotification // The application will enter the background
UIApplicationDidEnterBackgroundNotification // enter the background UIKeyboardWillShowNotification // UIKeyboardDidShowNotification is displayed on the keyboard. // UIKeyboardWillHideNotification is displayed on the keyboard. // hide the keyboard. // hide the keyboard.

 

6. Example:"

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.