2011-06-14 63 views
0

有沒有一種方法可以將iPhone發送給沒有特定接收器對象的對象發送消息,並進入另一個對象,收聽此類消息與對象(參數),並做需要什麼?iPhone - 發送消息「在空中」用於任何聽衆對象

我在NSNotification周圍搜索,但我沒有看到我應該做什麼。

+0

你在運行相同的應用程序在兩部手機之間是什麼意思? – deanWombourne 2011-06-14 22:22:55

+0

@deanWombourne:不,我的意思是在一個應用程序內。發佈編輯。 – Oliver 2011-06-14 22:23:56

回答

1

想要通知的對象需要註冊才能收到通知中心的通知。之後,當通知被髮布到通知中心時,通知中心將針對所有已註冊的過濾器進行檢查,並且將針對每個匹配過濾器採取相應的動作。

本例中的「過濾器」是一對(通知名稱,通知對象)。過濾器中的對象nil等同於任何對象(通知對象在匹配中被忽略)。該名稱是必需的。

例子:

/* Subscribe to be sent -noteThis: 
* whenever a notification named @"NotificationName" is posted to the center 
* with any (or no) object. */ 
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 
[nc addObserver:self selector:@selector(noteThis:) 
      name:@"NotificationName" 
     object:nil]; 

/* Post a notification. */ 
[nc postNotificationName:@"NotificationName" object:self userInfo:someDict]; 

/* Handle a notification. */ 
- (void)noteThis:(NSNotification *)note 
{ 
    id object = [note object]; 
    NSDictionary *userInfo = [note userInfo]; 
    /* take some action */ 
} 

有使用隊列和塊一個更現代的API,但我發現舊的API更易於說明和解釋。

+0

非常感謝。非常有幫助 ! – Oliver 2011-06-14 22:40:42

1

基本上,您將通知(NSNotification)發佈到共享類NSNotificationCenter。這裏有一個例子:

#define kNotificationCenter [NSNotificationCenter defaultCenter] 
#define kNotificationToSend @"a notification name as a string" 

//... Post the notification 

[kDefaultCenter postNotificationNamed:knotificationToSend withObject:nil]; 

想要聽任何類,增加了自身作爲觀察員到notifcation中心。你也必須刪除觀察者。

[kNotificationCenter addObserver:self selector:@selector(methodToHandleNotification) object:nil]; 

//... Usually in the dealloc or willDisappear method: 

[kNotificationCenter removeObserver:self]; 

您可以在通知中心做更多的事情。請參閱the NSNotificationCenter documentation fr完整參考。

+0

謝謝。我是在正確的方式。但是,如何將對象作爲參數發送?應該聽什麼? – Oliver 2011-06-14 22:33:15

+0

監聽對象只是一個過濾器,用於只監聽給定的對象。如果您偵聽一個零對象,則具有匹配名稱的所有通知都將起作用。發佈時,您可以發送一個對象和/或NSDictionary。查看更多文檔。 – Moshe 2011-06-14 22:38:59

0

我認爲NSNotification是消息對象本身,發送來聽什麼發送試試NSNotificationCenter。它有一個單獨的對象,所以發送消息:

NSNotification *notificationObj; 
NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; 
[center postNotification:notificationObj]; 

而另一類聽搭配:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(method:) object:nil]; 

確保類有method:方法。您可以擁有一個參數,即早期發送的NSNotification對象。 NSNotification對象具有[notificationObj object,您可以將其作爲發件人類發送的一段數據獲取。或者,如果您希望更具結構化,則可以使用[notificationObj userInfo]

你可以初始化notificationObj並用你想要的信息定製它。在NSNotificationCenter更多信息,你可以找到它

http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html#//apple_ref/occ/cl/NSNotificationCenter

或瞭解更多信息有關NSNotification本身

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotification_Class/Reference/Reference.html