Hong xiaoyaoxue iOS-nsnotificationcenter details

Source: Internet
Author: User
Tags notification center

Icationcenter center usage:

[Original] nsicationicationcenter may not be created in the class of the message receiver. You can put it in another class. instantiate it first, and then assign the value of observer to the new object.

Here, the observer is equivalent to the receiver, and the object is equivalent to the sender (poster ). By understanding this, you can use notifications more flexibly.

This problem occurs during iphone software development: After the app is opened, a method is run in the background, such as downloading an object. After the download is complete, you may need to call a method to refresh the interface, at this time, the callback in the downloaded function may not be available. Nsicationicationcenter (notification) is a good choice.

The usage of notifications is often quite simple:

1. Define notifications:

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(callBack)     name: @"back"    object: nil];

2. Define the method used in the notification:

- (void)callBack{NSLog(@"i am back.");}

3. Call Notification:

-(Void) getit {nslog (@ "get it."); // sends a notification [[nsicationicationcenter defaultcenter] postnotificationname: @ "back" Object: Self];}

 

Notificationcenter

[From] http://www.devdiv.com/home.php? MoD = Space & uid = 82357 & Do = Blog & id = 3835

Communications

Notification encapsulates event information, for example, the window is getting the focus or the network connection is disconnected. an object that needs to subscribe to an event (for example, an object that wants to know that its window is being edited will be closed) must be registered in the notification center, and then be notified when the event occurs. when an event occurs, a notification is sent to the notification center, and then the notification center immediately forwards the notification to all objects that have subscribed to the event. when necessary, notification will be cached in notification queue ....

Principle of notification

The most standard way to transmit information between two objects is to transmit a message-one object calls another object method. however, this method requires that the object that sends the message knows the receiver of the message and the type of message that it can receive. this will closely bind two objects-the most important thing is that this will couple two originally independent subsystems. to solve these problems, the broadcast model was proposed. the object is only responsible for sending the notification, and the nsicationicationcenter will be responsible for forwarding the notification to all related objects.

An nsnotification (notification in this article) contains a name, an object, and an optional dictionary. name is the identifier of notification. an object contains any type of objects that the notification sender wants to send ). dictionary is used to save other related things (if any ).

Any object can send notification. any object can be registered in the notification center to be notified when an event occurs. the notification center sends the received notification to all registered message recipients. the object that sends the notification. The objects in the notification and the objects that receive the notification can be the same object or three different objects. the object that sends the notification does not need to know any information about the recipient. however, the recipient must at least know the name of the notification and the key of the dictionary it contains (if any ).

Notification and Delegation

In terms of usage, the notification system is similar to the delegate system, but they have the following differences:

* The receiver of notification can be multiple objects, but only one delegate object can be. This prevents the return value.
* An object can receive any number of notifications it wants from the notification center, while delegate can only accept pre-defined delegate methods.
* The object that sends the notification does not know whether the recipient exists.

Notification centers

The notification center receives and sends notifications. when it receives notification, it notifies all recipients who meet the specified conditions. notification Information is encapsulated in nsnotification. the notification recipient registers in the notification center to obtain the notification sent by other objects. when an event occurs, an object sends the relevant notification to the notification center. the notification center distributes messages to each registered receiver. the object and recipient sending notification may be the same.

Cocoa contains two notification centers:

* Nsicationicationcenter class manages notifications within a single process.
* Nsdistributednotificationcenter manages cross-process notifications on a machine.

Nsnotificationcenter

Each process has a default notification center. You can obtain it by accessing the + defacenter Center Method of nsicationicationcenter. this type of notification center is responsible for managing the internal notifications of a single process. nsdistributednotificationcenter is required to manage notifications between different processes on the same machine.

The notification center sends the notification to the receiver in synchronous mode. that is to say, when sending a notification, it will not be returned unless all recipients receive and process the notification. to send an asynchronous notification, you need to use notification queue.

In a multi-threaded application, notification is always in the same thread as the sender, but the receiver can be in other threads.

Nsdistributednotificationcenter

Each process has a default distributed notification center. You can obtain it by accessing the + defacenter Center Method of nsdistributedicationicationcenter. this type of notification center manages notifications between multiple processes on a machine. if you need to communicate between multiple machines, use distributed objects.

It is very expensive to send a distributed notification. notification is first sent to a system-level server and then distributed to each registered process separately. theoretically, the latency from sending to receiving is infinite. in fact, if too many notifications are sent to the server, the notification queue on the server may be full, which may cause notification loss.

Distributed notification is sent out in the main loop of a process. A process must have a main loop running inside it, such as nsdefaultrunloopmode, before receiving distributed notification. if the receiving process is multi-threaded, the notification is not necessarily accepted by the main thread. generally, notification is distributed to the main loop of the main thread, but other threads can receive the notification.

A general type of notification center can register the notifications of all objects, but the distributed notification center can only register string-type notifications. because the sender and receiver may be in different processes, the objects contained in the notification cannot point to the same object. therefore, the distributed notification center can only accept notifications that contain string types. notification will match based on strings.

Notificationcenter usage 

1. Define a method

Update

2. subscribe to notifications

[[Nsicationcenter center defacenter center] addobserver: Self selector: @ selector (update) Name: @ "Update" Object: Nil]

3. Where the notification message is to be sent

[[Nsicationcenter center defacenter center] postnotificationname: @ "Update" Object: Nil];

----------------------------

Notice of virtual keyboard display and disappearance

[[Nsicationcenter center defacenter center] addobserver: Self

Selector: @ selector (keyboardwasshown :)

Name: uikeyboarddidshownotification

Object: Nil];

[[Nsicationcenter center defacenter center] addobserver: Self

Selector: @ selector (keyboardwashidden :)

Name: uikeyboarddidhidenotification

Object: Nil];

------

-(Void) keyboardwasshown :( nsnotification *) anotification {

If (keyboardshown)

Return;

Nsdictionary * info = [anotification userinfo]; // get Notification Information

// Get the size of the keyboard.

Nsvalue * avalue = [info objectforkey: uikeyboardframebeginuserinfokey];

Cgsize keyboardsize = [avalue cgrectvalue]. size;

// Resize the scroll View

Cgrect viewframe = [scrollview frame];

Viewframe. Size. Height-= keyboardsize. height;

// Scroll the active text field into view

Cgrect textfieldrect = [activefield frame];

[Scrollview scrollrecttovisible: textfieldrect animated: Yes];

Keyboardshown = yes;

}

// Called when the uikeyboarddidhidenotification is sent

-(Void) keyboardwashidden :( nsnotification *) anotification {

Nsdictionary * info = [anotification userinfo];

// Get the size of the keyboard.

Nsvalue * avalue = [info objectforkey: uikeyboardframeenduserinfokey];

Cgsize keyboardsize = [avalue cgrectvalue]. size;

// Reset the height of the scroll view to its original value

Cgrect viewframe = [scrollview frame];

Viewframe. Size. height + = keyboardsize. height;

Scrollview. Frame = viewframe;

Keyboardshown = no;

}

The official documents are described as follows:

Postnotificationname: object: userinfo:

Creates a notificationA given name, sender, and informationAnd posts it to the receiver.

-(Void) postnotificationname :( nsstring *) IcationicationnameObject :( ID) IcationicationsenderUserinfo :( nsdictionary *) UserinfoParameters
Icationicationname

The name of the notification.

Icationicationsender

The object posting the notification.

Userinfo

Information about the notification. may benil.

From the above we can see that the object represents the sender !! Instead of sending parameters. The parameters to be sent can be placed in information, which is of the nsdictionary type.

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.