2012-02-23 48 views
-1

我有兩個類,A類和B類。在一個課程中完成操作時發送通知?

A類有一個方法

-(void)methodA:(id)sender 
{ 

} 

和B類有一個方法

-(void)methodB:(id)sender 
{ 

} 

現在我有一些工作是發生在methodA,所以一旦完成,我想從methodA發送一個通知到methodB:所以我可以做一些基於通知的操作。

那麼我該如何做到這一點?任何人都可以引導我,因爲我是obj-c的新手?

+1

可能重複的[如何發送和通過NSNotificationCenter在Objective-C接收消息?](http://stackoverflow.com/questions/2191594/how-to-send-and-receive-message-through- nsnotificationcenter合目標c) – Caleb 2012-02-23 23:07:24

回答

1

使用委託。從維基簡單的代碼:訪問http://en.wikipedia.org/wiki/Delegation_pattern

  • 委託是一個對象,其對象(一般)調用來處理或特定事件或行動做出迴應。
  • 你必須「告訴」一個接受你想成爲委託的委託的對象。這是通過調用[object setDelegate:self]完成的;或設置object.delegate = self;在你的代碼中。
  • 充當委託的對象應實現指定的委託方法。該對象通常在協議中定義方法,或者在NSObject上通過類別定義爲默認/空方法或兩者。 (正式的協議方法可能更乾淨,特別是現在Objective-C 2.0支持可選的協議方法。)
  • 當發生相關事件時,調用對象將檢查委託是否實現匹配方法(使用-respondsToSelector :)並在該方法調用時調用該方法。然後,代表在控制權返回給調用者之前已經有了控制權去做任何必須做出的響應。
0

最簡單的方法。

在B類的-(id)initWithNibName: Bundle:中,您需要添加註冊NSNotifications。

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
     if (self) { 

     // Custom initialization   
     [[NSNotificationCenter defaultCenter] addObserver:self 
                selector:@selector(methodB:) 
                 name:@"methodAFinished" 
                object:nil]; 

     } 

     return self; 

} 

然後你需要做的的A類的了methodA如下:功能。

- (void)methodA:(id)sender { 

     // Once you have completed your actions do the following 

     [[NSNotificationCenter defaultCenter] postNotificationName:@"methodAFinished" object:nil]; 

} 

- (void)methodB:(id)sender { 

     // This will then be called in the other class, do whatever is needed in here. 

} 

希望對你有用!

另外,別忘了,在B類的-(void)viewDidDisappear:animated函數中,您需要取消註冊通知。

- (void)viewDidDisappear:(BOOL)animated { 

     [super viewDidDisappear:animated]; 
     [[NSNotificationCenter defaultCenter] removeObserver:self]; 

} 

這應該完成你所要求的。請加上您的問題,如果這不是你正在工作或評論下面,我可以糾正我的答案。

0

註冊在B類觀察員,如:

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

與後從類的通知。類似的:

[NSNotificationCenter defaultCenter] postNotificationName:@"notificationname" object:nil]; 

在B類取出觀察,當它被釋放像

[[NSNotificationCenter defaultCenter]removeObserver:self];