有沒有一種方法可以將iPhone發送給沒有特定接收器對象的對象發送消息,並進入另一個對象,收聽此類消息與對象(參數),並做需要什麼?iPhone - 發送消息「在空中」用於任何聽衆對象
我在NSNotification周圍搜索,但我沒有看到我應該做什麼。
有沒有一種方法可以將iPhone發送給沒有特定接收器對象的對象發送消息,並進入另一個對象,收聽此類消息與對象(參數),並做需要什麼?iPhone - 發送消息「在空中」用於任何聽衆對象
我在NSNotification周圍搜索,但我沒有看到我應該做什麼。
想要通知的對象需要註冊才能收到通知中心的通知。之後,當通知被髮布到通知中心時,通知中心將針對所有已註冊的過濾器進行檢查,並且將針對每個匹配過濾器採取相應的動作。
本例中的「過濾器」是一對(通知名稱,通知對象)。過濾器中的對象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更易於說明和解釋。
非常感謝。非常有幫助 ! – Oliver 2011-06-14 22:40:42
基本上,您將通知(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完整參考。
我認爲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
更多信息,你可以找到它
或瞭解更多信息有關NSNotification
本身
你在運行相同的應用程序在兩部手機之間是什麼意思? – deanWombourne 2011-06-14 22:22:55
@deanWombourne:不,我的意思是在一個應用程序內。發佈編輯。 – Oliver 2011-06-14 22:23:56