Here is a notification between different objects, not a local notification.
Beginning to play, very scratching his heads, and then found that the original object is only the process of init problem.
First, create a simple, single-controller project.
Then open its viewcontroller.m file
@interface Viewcontroller ()
@property Notifyobserver *obj; Here is the key, there should be a property is another to notify the class, I wrote in the viewdidload inside, the result of dead and alive Notice no response, in fact, the reason is this object in the Viewdidload method after the automatic destruction, but also notify a fart.
@end
@implementation Viewcontroller
-(void) Viewdidload {
[Super Viewdidload];
Self.obj=[[notifyobserver alloc] init]; Here, an object to notify is init.
Notifyobserver *obj=[[notifyobserver alloc] init]; Before it was so written, tossing for two hours, you should smoke yourself ....
}
-(void) didreceivememorywarning {
[Super didreceivememorywarning];
}
-(Ibaction) notifybuttonpressed: (ID) Sender {
NSLog (@ "pressed");
Here began to inform, but also left a question is how to get userinfo, regardless, anyway sent a notice named Updatemessage, the content is my object.
Nsnotification *notification = [[Nsnotification alloc] initwithname:@ "Updatemessage" object:@ "My Object" userInfo:@{@ " Status ": @" Success "}];
[[Nsnotificationcenter Defaultcenter] postnotification:notification];
}
@end
Anyone who wants to receive this notice is going to register
@implementation Notifyobserver
-(ID) init{
NSLog (@ "Init");
In the Init method registers oneself is an observer, then defines oneself only receives "the Updatemessage" the notice, does not have the mess all informs me, moreover, if notifies, the trouble runs the Update method, remembers behind has a ":" means oneself is the method which takes the formal parameter, A native speaker of Java laughs and doesn't speak
[[Nsnotificationcenter defaultcenter]addobserver:self selector: @selector (update:) name:@ "Updatemessage" Object:nil ];
return self;
}
-(void) dealloc{
Remember to remove the registration when this object is to be destroyed
[[Nsnotificationcenter Defaultcenter] removeobserver:self];
}
This update method is the notification callback, and once the notification comes, it is troublesome to run the method.
-(void) Update:(nsnotification *) notification
{
NSLog (@ "Update");
nsstring* str = (nsstring*) [notification object];//here take out the string just from over
NSLog (@ "%@", str);
}
@end
Almost a day to learn to inform notification, slow enough ....
More and more think iOS is simple ah .....
Notifications, delegates, these two design modes iOS play ...
Notifications for iOS notification