Nsicationicationcenter message center in iOS Design Mode
The message center mode is similar to the KVO mode. The difference is that the KVO mode is intended to listen to a change in the corresponding value, and proceed with a corresponding action of the method, while the message center is, broadcast: it is like a broadcast base station that sends a message. It can receive this message in all the places where listening is added, and make the same action for different living conditions, with a wider range, more powerful
// Add a message center listener (adding an observer can also be said to add a listener) [[nsicationicationcenter defacenter center] addObserver: self selector: @ selector (myNotification :) name: @ "test1" object: nil];
It monitors whether the entire value of test1 has been sent to the entire message. The Listener is in the self class. If it listens, The myNotification method is triggered.
// Send messages through the message center,
// Note: In the message center, First listen and then send messages
// Object: The sent parameter [[nsicationicationcenter defacenter center] postNotificationName: @ "test1" object: arra];
// This method can be used in any class of this project, so that it can communicate with other places.
// For example, if there are five pages, a message center is created in the first four pages to listen to a message @ "change" // on the fifth page, through the message center, send a @ "change" message, so that the first four pages can receive the message, and then make the corresponding action // be sure to note that the message center listener must be created before sending the message, // The key to solving this problem when using various cyclic functions flexibly
Let's look at an instance.
Two interfaces: interface 1 interface 2 interface 1 create a message center to listen to messages, interface 2-bed message center, send messages with Parameters
// Create a message center in interface 1 [[NSNotificationCenter defacenter center] addObserver: self selector: @ selector (myNotification :) name: @ "test1" object: nil];
In interface 1, implement the listening method // execute this method when listening to messages-(void) myNotification :( NSNotification *) n {// retrieve the object from received message n, that is, the parameters loaded in the message.
// NSString * param = [n object];
NSArray * arr = [n object];
NSLog (@ "% @", arr );
}
In interface 2, send an array as the parameter NSArray * arra = [NSArrayarrayWithObjects: @ "a", @ "d", nil];
// Send messages through the message center,
// Note: In the message center, First listen and then send messages
// Object: The sent parameter [[nsicationicationcenter defacenter center] postNotificationName: @ "test1" object: arra];