2012-01-30 26 views
1

我正在研究NSNotificationCenter。這裏是我的代碼通過伊娃槽NSNotificationCenter

Observer.m

//note init method is not complete here 

    -(id) init 
    { 
    [[NSNotificationCenter defaultCenter] 
      addObserver:self 
      selector:@selector(reciveTestNotification:) 
      name:@"TestNotification" object:nil]; 

    } 

    -(void)reciveTestNotification:(NSNotification *)notification 
    { 
     if([[notification name] isEqualToString:@"TestNotification"]) 
     { 
      NSLog(@"Succesfuly received the test notification"); 
     } 
    } 

Osender.m

-(void)reciveTestNotification:(NSNotification *)notification 
{ 
    if([[notification name] isEqualToString:@"TestNotification"]) 
    { 
     NSLog(@"Succesfuly received the test notification"); 
    } 
} 

我認爲我已瞭解NSNotification是如何工作的,但如何通過NSNotification通過伊娃?

比方說Osender.h有這樣的代碼

Osender.h

@interface Osender : NSObject 
{ 
    IBOutlet UITextField *txt; 
} 

@property (nonatopic, copy) IBOutlet (UITextField *) *txt 

如何通知reciveTestNotification和數據傳遞到它時,用戶類型或改變TXT的東西嗎?

回答

2

NSNotification類有,你可能需要額外的數據屬性發送您的通知,userInfo

你發佈這樣的:

NSDictionary *userInfo = [NSDictionary dictionaryWithObject:txt forKey:@"textField"]; 
[[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:self userInfo:userInfo] 

,並得到它是這樣的:

- (void)reciveTestNotification:(NSNotification *)notification 
{ 
    UITextField *textField = [notification.userInfo objectForKey:@"textField"]; 
} 

現在textField有關於你UITextField

+0

我得到語義問題:未找到方法'-hasObjectForKey:'。我想這是因爲通知不響應該方法? – nedich 2012-01-30 12:33:37

+0

固定。我的錯。你不必檢查'NSDictionary'中是否存在一個對象。如果沒有對象,它只返回'nil'。 – 2012-01-30 13:27:00

1

您可以將自定義數據放入通知的userInfo,這是一個NSDictionary實例。您需要確保通知海報中字典中創建的密鑰與通知消費者期望的密鑰相同。

+0

你能舉個例子嗎? – nedich 2012-01-30 11:43:26

0

使用NSNotificationCenter

的這種方法
- (void)postNotificationName:(NSString *)notificationName object:(id)notificationSender userInfo:(NSDictionary *)userInfo 

,並設置用戶信息與數據一個NSDictionary要傳遞:

NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:@"object", @"key", nil]; 
[[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:nil userInfo:infoDict];