觀察者

使用消息機制的步驟:post

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];
相關文章
相關標籤/搜索