1. Define a method
-(void) update{}
2. Object registration, and connected messages
[[Nsnotificationcenter Defaultcenter]
Addobserver:self selector: @selector (update) name:@ "Update" Object:nil]
3. Where you want to send a notification message
[[Nsnotificationcenter Defaultcenter]
postnotificationname:@ "Update" Object:nil];
Specifically how to use notifications
Http://blog.sina.com.cn/s/blog_5df7dcaf0100c0q2.html
////////////////////////////////////////
14th Chapter: Using Notifications
The user may have used Raiseman and opened several documents, and then he found that the purple background color was really bad for reading the body of the document.
He then opens the Preferences panel to modify the background color, but it is disappointing that the background color of the existing document does not change.
So, this user may write to you to tell you this. You may reply: "Defualts will be read when document is created,
Save document Open "In fact, the user wants to explain that he wants the program to immediately refresh the document that is already open. If so, what should be done?
Do we need to record all the open documents with a list?
---What is notification? ---
This requirement is actually easy to achieve. Each running application has a member variable of Nsnotificationcenter.
It functions like a public bar. Object registration follow a certain notification (if someone picks up a puppy, tell me).
We call these registered objects observer. Other objects will send notifications to center (I picked up a puppy).
Center forwards the notifications to all registered objects that are interested in the notification. We call these notification objects poster.
Many of the standard cocoa classes send notifications: When the size is changed, window will send notification;
When you select a row in Table view, table view sends notification, and we can view the notification sent to the standard cocoa object in the online Help document.
In our example, we register the Mydocumet object as observer. The preference controller sends a notification when the user changes color.
Mydocument changes background color after receiving the notification
Before the mydocument object is released, we must remove our registered observer from Notification Center. Generally, we do this in the Dealloc method.
--Notifications is not what--
When the handlers hear notification center, they may associate IPC (interprocess communication). They think:
"I create a observer in a program and then send a notification in another program." This design has no way of working,
Notification Center allows different objects in the same program to Tongxu, which cannot span different programs [notification is the Observer pattern in design mode,
Cocoa has implemented this pattern for us, just as Java has the same implementation]
--Nsnotification and Nsnotificationcenter
The notification object is very simple. It is the information package that poster to provide to observer. The notification object has two important member variables:
Name and object. The general object is pointing to poster (in order for observer to be able to call back to poster when accepting notification)
So, notification has two ways
-(NSString *) name
-(ID) object
Nsnotificaitoncernter is the brain of the architecture. It allows us to register observer objects, send notification, revoke observer object registration
Here are some of its common methods
+ (Nsnotificationcenter *) defaultcenter
Returns a notification Center [class method that returns a global object, one-piece mode. Cocoa Many of the global objects are implemented in a similar way]
-(void) Addobserver: (ID) anobserver
Selector: (SEL) Aselector
Name: (NSString *) notificationname
Object: (ID) anobject
Register Anobserver object: Accept the name of Notificationname, sender is AnObject notification. When AnObject sends a name
When the notification is Notificationname, the Aselector method of Anobserver is called, and the parameter is notification 14.1
. If Notificationname is nil. Then notification center forwards all notification sent by ANOBJECT to Observer
. If AnObject is nil. Then Notification Center will send all notification with the name NOTIFICATIONNAME to Observer
-(void) Postnotification: (nsnotification *) notification
Send notification to Notification Center 14.2
-(void) Postnotificationname: (NSString *) aName
Object: (ID) anobject
Create and send a notification
-(void) Removeobserver: (ID) Observer
Remove Observer
--Send a notification--
Sending notification is one of the simplest steps, so we start with it. When we receive the Changebackgroundcolor: message,
The Preferencecontroller object sends a notification.
We named notification @ "Bnrcolorchanged" and we use a global constant to specify it. (an experienced programmer would use a prefix,
This avoids the notification confusion with other component definitions) Open PreferenceController.h Add the following external declaration
extern NSString * Const bnrcolorchangednotification;
Defining Constants in PREFERENCECONTROLLER.M
NSString * Const Bnrcolorchangednotification = @ "bnrcolorchanged";
Modify Changebackgroundcolor in Preferencecontroller.m: Method
-(Ibaction) Changebackgroundcolor: (ID) sender
{
NSColor *color = [Colorwell color];
NSData *colorasdata =
[Nskeyedarchiver Archiveddatawithrootobject:color];
[[Nsuserdefaults Standarduserdefaults] Setobject:colorasdata
Forkey:bnrtablebgcolorkey];
Nsnotificationcenter *NC = [Nsnotificationcenter defaultcenter];
NSLog (@ "sending notification");
[NC postnotificationname:bnrcolorchangednotification Object:self];
}
--register as observer--
To register a observer, we must provide several numbers: the object to be observer; the name of the notification of interest;
The method to invoke when notification is sent. We can also specify notification to focus on the object. (For example, we need
Focus on the resize of a particular window notification)
Edit the Init method of the mydocument class
-(ID) init
{
if (![ Super Init])
return nil;
Employees = [[Nsmutablearray alloc] init];
Nsnotificationcenter *NC = [Nsnotificationcenter defaultcenter];
[NC addobserver:self
Selector: @selector (handlecolorchange:)
Name:bnrcolorchangednotification
Object:nil];
NSLog (@ "Registered with Notification Center");
return self;
}
Also in the Dealloc method, remove mydocument from Notification Center
-(void) dealloc
{
[Self setemployees:nil];
Nsnotificationcenter *NC = [Nsnotificationcenter defaultcenter];
[NC removeobserver:self];
[Super Dealloc];
}
--handling notification--
When a notification occurs, the Handlecolorchange: method is called. For now, we're simply printing some log in the method.
-(void) Handlecolorchange: (nsnotification *) Note
{
NSLog (@ "Received notification:%@", note);
}
Compile and run the program and see the log we want.
--UserInfo Dictionary--
The notification object is poster, and if we want to notification the object to pass more information,
We can use the user info dictionary. Each notification object has a variable called UserInfo, which is a Nsdictionary object,
Used to store other information that the user wants to pass along with notification to observer. Mydocument will use it to get the color to change.
Add UserInfo in PREFERENCECONTROLLER.M
-(Ibaction) Changebackgroundcolor: (ID) sender
{
NSColor *color = [sender color];
NSData *colorasdata;
Colorasdata = [Nskeyedarchiver Archiveddatawithrootobject:color];
[[Nsuserdefaults Standarduserdefaults] Setobject:colorasdata
Forkey:bnrtablebgcolorkey];
Nsnotificationcenter *NC = [Nsnotificationcenter defaultcenter];
NSLog (@ "sending notification");
Nsdictionary *d = [Nsdictionary dictionarywithobject:color
forkey:@ "Color"];
[NC postnotificationname:bnrcolorchangednotification
Object:self
USERINFO:D];
}
In MYDOCUMENT.M, read from userinfo to color
-(void) Handlecolorchange: (nsnotification *) Note
{
NSLog (@ "Received notification:%@", note);
NSColor *color = [[Note userInfo] objectforkey:@ "color"];
[TableView Setbackgroundcolor:color];
}
Open several windows and change the background color, and now the background color of those open windows changes immediately.
--thinking--
Usually when you set your own object to cocoa a standard object's delegate, you may also be interested in the notification of that standard object.
For example, we implement a window's delegate to handle Windowshouldclose: We may have a nswindowdidresizenotification
Such notification are interested.
If a cocoa standard object has a delegate, and it also sends notification, the Cocoa object will automatically register its delegate object
Become observer to accept your notification. If we achieve a delegate, then delegate[is our object]
How to declare to accept notification? [What is the name of the method?]
The method name is actually very simple: take the notification name as the benchmark, first remove the NS prefix, and then change the first letter to lowercase. After removing the notification in the back,
Then add a colon:. For example, to be able to accept the nswindowdidresizenotification of a window, delegate can implement the method:
-(void) Windowdidresize: (nsnotification *) anotification
This method is called automatically when the window changes size. For Nswindow, we can find similar notification in. h or in the Help documentation.
To implement the notification method.
--Challenges--
When the program is no longer in the active state, let the program issue beep. When Unactive, NSApplication will send
Nsapplicationdidresignactivenotification's Notificaiton. And our AppController is the delegate of NSApplication.
function Nsbeep () can be used to emit beep sound