Simple use of nsnotification in iOS
Haven't written a blog for a long time, always encounter problems check, today is an old question, think about, or record! Today in the project development encountered a timely disposition of the problem, think of the decision to use notification after the implementation, but the realization of the notice has been forgotten, to the online check, think this is a check several times the problem, I think it is necessary to record a bit, but also write to let yourself remember also more clear some! This article just records a little bit of Nsnotification's simple use method (due to poor writing, will often record some of the problems encountered, several times can tell the reason, the process of slow efforts!) )。
1.NSNotification is responsive programming
Common methods for senders:
1. Create a notification and send
Nsnotification *notification = [[Nsnotification alloc] initwithname:@ "Refresh" object:self Userinfo:nil];
[[Nsnotificationcenter Defaultcenter] postnotification:notification];
2. Send a notification name directly (no additional messages required)
[[Nsnotificationcenter Defaultcenter] postnotificationname:@ "Refresh" object:self];
3. Send notifications and create a separate userinfo
Nsdictionary *userinfo = @{@ "name": @ "Xiaoyou"};
[[Nsnotificationcenter Defaultcenter] postnotificationname:@ "Refresh" object:self Userinfo:userinfo];
Common methods for receiving parties:
1, set the monitoring/*** add monitoring */-(void) addobservertonotification{[[nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (updatelogininfo:) name:@ "Refresh" Object:nil];}
2. Listen to the execution method/*** update the login information, note that you can get the notification object here and read the additional information */-(void) Updatelogininfo: (nsnotification *) notification{
Nsdictionary *userinfo=notification.userinfo;
NSObject *object = Notification.object;
Refresh Data
[Self loaddata];
}
3. Remove Monitor-(void) dealloc{//Remove the listener [[Nsnotificationcenter Defaultcenter] removeobserver:self];}
2. Precautions
The receiver must remove the listener in the destructor method, which is the code specification.
Nsnotification easy to use in IOS projects