IOS Amusing design mode-notification

Source: Internet
Author: User

"Preface Introduction"

A design pattern for iOS, the Observer Observer mode (also called publish/subscribe, i.e. Publich/subscribe mode).

The Observer pattern includes the notification mechanism (notification) and the KVO (key-value-observing) mechanism.

In this article, we will present a design pattern of the notification mechanism that is often used in daily projects.

Notification mechanism

The mechanism of delegation is the communication between the objects of "one-on", and the notification mechanism is the communication between the objects of "one-to-many" broadcast.

First, what is it? " Examples of Life problems "

"SMS Weather Forecast"

When Class A sends a message to the notification center, the class B group that is registered as a user (Observer) receives the corresponding notification and responds.

Second, what is the use? "Apps in Code"

How do you pass data between different classes?

There are several methods: attribute delivery, proxy protocol, and notification.

Notification: The method created in Class A, executed in class B, and can be used to carry data to each other;

Three, what is the difference? "Different from other" notifications? 】

Frequently mentioned notifications, with "broadcast notifications", "Local Notifications", "Push Notifications"

This article describes the broadcast notification, is a mechanism to implement the observer pattern, you can communicate data between multiple objects in an application.

Local notifications and push notifications are primarily for sending "notification prompts" to users, such as warning prompts, sounds, vibrations, and red numbers on the mark.

The first is "Send notifications locally" to the user, and the second is sent by a third-party app to Apple's official remote server, which is then sent to the user by the server "push notifications".

Iv. Product Manager: The usual, the code to get ~ "Concrete Implementation"

Process:

    • In the notification mechanism, all objects that need (or are interested in) receiving information about a notification can be receivers, first registered as observers.
    • Once registered, the Notification Center broadcasts notification messages sent by the Publisher to the observers who have registered the notification. The observer can only receive information from the Notification center and cannot know who sent the notification.
    • Finally, the recipient does not want to pay attention to the information of the notice, the Notification Center can be released from the registration information, and then no longer receive notification.

1. Get the notification hubs (Nsnotificationcenter) object: (As with the access to the mobile operator's SMS center, as a medium)

notification hubs are required for publishing, registering, and releasing notifications, and are responsible for assisting with message communication between different objects and classes.

[Nsnotificationcenter  defaultcenter];   It is important to note that the notification Center is also a singleton

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

A. Send notifications as a publisher for Class A:

There are three ways to use it:

-(void) Postnotification: (nsnotification *) notification; -(voidObject:(ID) anobject; -(voidObject:(ID) anobject userInfo: (nsdictionary *) Auserinfo;
    • Postnotificationname: Specifies the name of the message;
    • Object: Specifies the sender of the message;
    • UserInfo: A vector used to pass parameters in a notification, passed by placing the parameter in the userInfo of the nsdictionary type. For example: nsdictionary *dict = [notification UserInfo];

A third method is generally used, and can be set to nil if the parameter is not required .

B. registration Notice, JOIN the Observer:

As the Observer type B registration notice, to monitor:

-(void) Addobserver: (ID) Observer selector: (SEL) aselector name: (Nullable NSString *) AName object: (Nullable ID) anobject ;
In the @selector, for the callback method, the notification is processed accordingly in this class, name is the notification name, object;

Analysis:

    • object ==  nilselfnswindowdidbecomemainnotification notification message;
    • name  == nil, So the Observer will receive all messages of the object However, the order in which these messages are received is not determined.
    • Object == nil,name  == nil

For an arbitrary observer Observer, if there is no guarantee that the corresponding selector has this type of custom method (for example: MyMethod), you can use [observer respondstoselector : @selector (MyMethod:)]] to check.

So the complete addition of the observer process is:

if ([Observer Respondstoselector: @selector (MyMethod:)]) {        [[nsnotificationcenter Defaultcenter] Addobserver:o Bserver selector: @selector (MyMethod:) name:nswindowdidbecomemainnotification Object:nil];    }  

Of course there is another way to register the 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 callbacks in this method , and the queue parameter means that the module is in the queue.

However, this method is generally not used, so the first method is recommended for observer creation.

C. Removal of notifications

Because the notification hub does not retain the Observer object, the registered object must be logged off before it is released, and if not, the notification hub sends a message to the released observer object when the notification reappears, causing the app to crash.

Under ARC, the system will automatically reclaim useless notification object memory, but because of the system recycling mechanism arc has a certain delay, so even if there is no error, it is recommended to develop a habit, the notification manually released useless notice.

There are 2 ways to remove:

Release all notifications
-(void) Removeobserver: (ID) observer;
Release notification with name AName-(void) Removeobserver: (ID) Observer name: (Nullable NSString *) AName object: (nullable ID) anobject;

Typically in a view controller, you cansend a cancellation message in "Didreceivememorywarning:":

-(void) didreceivememorywarning{    [Super didreceivememorywarning];    Remove the viewer    [[Nsnotificationcenter defaultcenter]removeobserver:self];}

Five, those years we used the system notification name ~

The system comes with a lot of useful notifications, we only need to register as the corresponding notification receiving object, you can change the notification status according to the corresponding data changes.

Some system notification names are as follows:

Uiapplicationdidfinishlaunchingnotification//Application start uiapplicationdidbecomactivenotification     //Enter the foreground Uiapplicationwillresignactivenotification   //applications will enter the background
Uiapplicationdidenterbackgroundnotification//into the background uikeyboardwillshownotification //keyboard will be displayed Uikeyboarddidshownotification //keyboard display complete uikeyboardwillhidenotification //keyboard is about to be hidden Uikeyboarddidhidenotification

Six, give a chestnut: "??"

There are 2 examples of this article:

    • One is the complete notification of the release, reception, cancellation process;
    • One is the application of the system notification name (in the first uiapplicationwillresignactivenotification
      As an example);

(By: Think the article too long do not want to see this paragraph of children's shoes, can also go to github download Ah left of the demo, their own pondering: Mydemo1, Mydemo2.

Click on the "DownLoad ZIP" button to do it. Generally use Safari browser download, ah left with the QQ browser seemingly can't download ... 囧

"This development environment: xcode:7.2 IOS Simulator:iphone6 by: Ah Left"

1. Complete notification of the release, receipt, cancellation process:

The UI controls are placed as follows, and the view, control's background can be set to a more obvious color, which makes it easy to observe:

A view creates a TextView to display the information passed by B view, a button to switch to B view;

b View creates a text box for updating information, and a button to update the text box's information and return to view a.

Then, click the A-Class button, and then control-drag the controller to the B-view and release the mouse, and in the pop-up selection box (e.g.) Select: "Present modally" is used to create the segue of the modal type between the A and B controllers.

Next, we need to create a new view Controller Class B Seocndviewcontroller:

Back in the storyboard, select the B View Controller, open the Identity Checker (the first row of the third option), and select the class: Seocndviewcontroller. This makes the code correspond to the view controller in the storyboard. (A view By default corresponds to Viewcontroller, if there is an error, you can check it.) )

Then we open the Auxiliary editor, control, drag the text in a view to connect to the corresponding output port, here we named "MyLabel".

In this manner, continue to connect the text box in class B to the code, named: "Mytextview",

Add behavior to the button for Class B, with the method name: "savebtn:",

Ah left still think the code is really point:

(ViewController.h)

#import <UIKit/UIKit.h> @interface viewcontroller:uiviewcontroller@property (weak, nonatomic) Iboutlet Uitextview *mylabel;   Each time the view is opened, listen for changes in Class B's data and display the update in this text view if there is a change. @end

(VIEWCONTROLLER.M)

#import "ViewController.h" @interface Viewcontroller () @end @implementation viewcontroller-(void) viewdidload {    [ Super Viewdidload];        1. Register as an observer and listen for notifications in B view    [[Nsnotificationcenter defaultcenter]addobserver:self selector: @selector (amethod:) Name: @ "Mynotificationname" Object:nil];} -(void) Amethod: (nsnotification *) notification{    //2. Gets the data that the notification carries, updates the label's text message    nsdictionary *dictdata = [ Notification UserInfo];    NSString *str = [Dictdata objectforkey:@ "Myuserinfokey"];    Self.myLabel.text = str;} -(void) didreceivememorywarning {    [super didreceivememorywarning];        3. Remove all notifications    [[Nsnotificationcenter defaultcenter]removeobserver:self];} @end

(SecondViewController.h)

#import <UIKit/UIKit.h> @interface secondviewcontroller:uiviewcontroller@property (weak, nonatomic) Iboutlet  Uitextfield *mytextview; text box for updating data passed to the Viewcontroller view-(ibaction) SAVEBTN: (UIButton *) sender;                        Save Back button Event @end

(SECONDVIEWCONTROLLER.M)

#import "SecondViewController.h" @interface Secondviewcontroller () @end @implementation secondviewcontroller-(void) viewdidload {    [Super viewdidload];} -(Ibaction) SAVEBTN: (UIButton *) Sender {        //return to view A and publish notification    [self dismissviewcontrolleranimated:yes completion:^{        //1. Creating information        that UserInfo carries NSString *str = self. Mytextview.text;        Nsdictionary *dictdata = [nsdictionary dictionarywithobject:str forkey:@ "Myuserinfokey"];        2. Release information        [[Nsnotificationcenter defaultcenter]postnotificationname:@ "Mynotificationname" Object:nil userInfo: Dictdata];}    ];} @end

Verify:

The first time a view of the text view does not show the data, click the button "OK Toggle page", open view B, enter the information in the text box (such as 123), click the "Save Back" button, in a view of the text view to see the updated information: 123.

By: Children's shoes are available on GitHub to download the left demo:mydemo1.

2. One is the application of the system notification name (take uiapplicationwillresignactivenotification as an example):

Uiapplicationwillresignactivenotification means that the application is about to enter the background at this moment.

First, the UI interface is created as follows, which is much simpler than the first example: a button + a UIView view of the display color.

Create aUIView control named "MyView", one method for the "CHANGECOLORBTN:" button behavior, to associate the Viewcontroller controller.

The code is as follows:

(ViewController.h)

#import <UIKit/UIKit.h> @interface viewcontroller:uiviewcontroller@property (weak, nonatomic) Iboutlet UIView * myview;-(ibaction) changecolorbtn: (UIButton *) sender; @end

(VIEWCONTROLLER.M)

#import "ViewController.h" @interface Viewcontroller () @end @implementation viewcontroller-(void) viewdidload {    [ Super Viewdidload];        1. Registered as an observer    [[Nsnotificationcenter defaultcenter]addobserver:self selector: @selector ( Applicationwillresignactivenotification:) name:uiapplicationwillresignactivenotification Object:nil];} 2. When the app is about to enter the background, call the notification callback method:-(void) Applicationwillresignactivenotification: (
Nsnotification *) notification{ //back to the background to change the view background to red; self.myView.backgroundColor = [Uicolor redcolor];} -(Ibaction) CHANGECOLORBTN: (UIButton *) Sender { //button to change the view background to yellow; Self.myView.backgroundColor = [Uicolor Yellowcolor];} @end

The view opens for the first time and the view is the default white:

Click the button and the view turns yellow:

Press and hold "Command+shift" and double-click H to enter the iOS multi-task bar;

or press and hold "Command+shift" and click H to return to the emulator main interface.

You can see that the view turns red.

And back to the app, the color is still red.

Indicates that when an application enters inactive state from an active state, the system automatically sends the "UIAPPLICATIONWILLRESIGNACTIVENOTIFICATION" notification, which, if there is a registered listener (Observer), executes the callback method.

By: Children's shoes are available on GitHub to download the left Demo:mydemo2.

IOS Amusing design mode-notification

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.