2011-12-08 27 views
0

我需要在目標c中創建可中斷的掛鉤。如果任何掛鉤回調中斷操作,可中斷掛鉤應該能夠中止操作。我想用NSNotificationCenter爲喜歡的:我可以更改通知中的用戶信息

NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; 
[userInfo setObject: [NSNumber numberWithBool: NO] forKey: @"interrupted"]; 
[notificationCenter postNotificationName: @"Operation A will happen" 
            object: self userInfo:userInfo]; 
if(![[userInfo objectForKey: @"interrupted"] boolValue]) 
{ 
    [self doOperationA]; 
} 

和鉤側

-(void) operationAWillHappen: (NSNotification *) note 
{ 
    if(someCondition) 
     [(NSMutableDictionary *)note.userInfo setObject: 
     [NSNumber numberWithBool: YES] forKey: @"interrupted"]; 
} 

我能否改變這樣的用戶信息?有沒有更好的方法在目標c中實現可中斷的鉤子?

回答

0

這完全是不安全的,如果你這樣做,你可能會崩潰你的應用程序。

我認爲你要找的是「delegate or delegation pattern」。

0

我的猜測是,它的工作原理,但由於API是一個不可變的對象,你不應該這樣做。如果今天碰巧工作,它可能會中斷。

您可以隨時在字典中傳遞自己,並讓偵聽器發送消息。

(我假設你想利用這個事實,即你可以擁有任意數量的聽衆 - 委派非常簡單,但你只能得到一個委託。)

相關問題