2011-07-25 47 views
4

所以我有一個應用程序與應用程序購買。 In App購買在FirstViewController中進行管理。當用戶購買產品時,我想向我的MainTableViewController發送通知以重新加載表格數據並顯示在應用內購買時購買的新對象。所以基本上我想發送從A類到B類的通知,然後B類重新加載tableview的數據。我曾嘗試使用NSNotificationCenter,但沒有成功,但我知道它可能與NSNotificationCenter我只是不知道如何。發送NSNotification從classA到classB

回答

24

在A類:發佈通知

[[NSNotificationCenter defaultCenter] postNotificationName:@"DataUpdated" 
                 object:self]; 

在B類:第一登記通知,並寫至處理它的方法。
您可以爲該方法提供相應的選擇器。

// view did load 
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(handleUpdatedData:) 
              name:@"DataUpdated" 
              object:nil]; 

-(void)handleUpdatedData:(NSNotification *)notification { 
    NSLog(@"recieved"); 
    [self.tableView reloadData]; 
} 
+0

不工作:( – JonasG

+1

應該。你不需要更多的運行的通知。如果CLASSA更新一些數據,確保這些變化反映在ClassB的,你也可以用通知給ClassB的一個值,但'reloadData'會讓tableView再次詢問它的數據源。 – 2011-07-25 11:49:25

+0

好了, - (void)updated {[self.tableView reload data];}在通知發送時不會被調用,請檢查你的代碼,我試圖修改代碼,但它並沒有幫助 – JonasG

0

也許你試圖從另一個線程發送通知? NSNotification不會從另一個線程傳遞給觀察者。

+0

我如何知道它是否從另一個線程發送? – JonasG

+0

嘗試比較[NSThread currentThread]在你通知觀察的類中[NSThread mainThread]產生通知的地方。 –

+1

還要確保,當你添加觀察者時你沒有指定**對象**。 –

8

好吧我加入多一點信息,以文斯的回答

在A類:發佈通知

[[NSNotificationCenter defaultCenter] postNotificationName:@"DataUpdated" 
                object:arrayOfPurchasedObjects]; 

在B類:先註冊通知,並寫入的方法處理它。
您可以爲該方法提供相應的選擇器。在發佈通知之前確保您的B班已分配,否則其他通知將無法使用。

- (void) viewDidLoad { 
// view did load 
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(handleUpdatedData:) 
              name:@"DataUpdated" 
              object:nil]; 
} 

-(void)handleUpdatedData:(NSNotification *)notification { 
    NSLog(@"recieved"); 
    NSArray *purchased = [notification object]; 
    [classBTableDataSourceArray addObjectsFromArray:purchased]; 
    [self.tableView reloadData]; 
} 

- (void) dealloc { 
    // view did load 
    [[NSNotificationCenter defaultCenter] removeObserver:self 
               name:@"DataUpdated" 
               object:nil]; 
    [super dealloc]; 
} 
+0

thx但它不工作,我也使用NSUserdefaults來識別應用程序購買是否完成,所以我不需要添加對象到數組。 – JonasG

+0

對於新人(我),上面的答案中有一個錯誤,'postNotficationName'拋出錯誤,'postNotificationName'(與另一個'我')糾正它。 (感謝Rahul Vyas幫助澄清通知過程)。 – tmr

+0

你的回答@RahulVyas有一個錯字,它不是「postNotficationName」 它是「postNotificationName」 –

相關問題