1. 觀察者注冊消息通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUserProfileSuccess:) name:@"Notification_GetUserProfileSuccess" object:nil];
notificationObserver 觀察者 : self
notificationSelector 處理消息的方法名: getUserProfileSuccess
notificationName 消息通知的名字: Notification_GetUserProfileSuccess
notificationSender 消息發送者 : 表示接收哪個發送者的通知,如果第四個參數為nil,接收所有發送者的通知
2. 發送消息通知
//UserProfile Is A Model
//@interface UserProfile : NSObject
[[NSNotificationCenter defaultCenter] postNotificationName:@"Notification_GetUserProfileSuccess" object:userProfile userInfo:nil];
notificationName 消息通知的名字: Notification_GetUserProfileSuccess
notificationSender 消息發送者: userProfile
3. 觀察者處理消息
- (void) getUserProfileSuccess: (NSNotification*) aNotification { self.userProfile = [aNotification object]; lblName.text = self.userProfile.Name; lblEENO.text = self.userProfile.EENO; lblNric.text = self.userProfile.NRIC; lblBirthday.text =self.userProfile.Birthday; lblHireDate.text = self.userProfile.Hiredate; txtMobilePhone.text = self.userProfile.Mobile; txtEmail.text = self.userProfile.Email; }
NSNotification 接受到的消息信息,主要含:
Name: 消息名稱 Notification_GetUserProfileSuccess
object: 消息發送者 userProfile
userInfo: 消息傳遞的數據信息
4. 觀察者注銷,移除消息觀察者
雖然在 IOS 用上 ARC 后,不顯示移除 NSNotification Observer 也不會出錯,但是這是一個很不好的習慣,不利於性能和內存。
注銷觀察者有2個方法:
a. 最優的方法,在 UIViewController.m 中:
-(void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; }
If you see the method you don't need to call [super dealloc]; here, only the method without super dealloc needed.
b. 單個移除:
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"Notification_GetUserProfileSuccess" object:nil];
本文首發於,博客園,請搜索:博客園 - 尋自己,查看原版文章
本文首發地址:IOS 消息機制(NSNotificationCenter) - http://www.cnblogs.com/xunziji/p/3257447.html
