2013-04-09 48 views
1

我有兩個分離的類FirstController和SecondController,用故事板創建。問題是我想調用SecondController.m中的方法,FROM FirstController。例如。 :IOS:在另一個控制器中調用方法

SecondController.m

-(void)myMethod:(CGPoint)pt {...} // It's important that there is a paramterer 

FirstController.m

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
    // Call myMethod 
} 

如何做到這一點的最簡單的方法?

更新: 我想使用的通知從 'aBilal17' 鏈接:

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"updateLeftTable" 
               object:nil]; 
[[NSNotificationCenter defaultCenter] addObserver:self 
            selector:@selector(checkRes:)  name:@"updateLeftTable" object:nil]; 

(..)

-(void)checkRes:(NSNotification *)notification 
{ 
    if ([[notification name] isEqualToString:@"updateLeftTable"]) 
    { 
     [myMethod ? 
    } 
} 

在其他類:

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

但現在,如何使用這個來傳遞我的CGPoint參數?

+0

你看了什麼?關於這種在stackoverflow上的事情有數百個問題。 – Popeye 2013-04-09 14:53:10

+0

除非您正在討論委託協議或通知,否則您可能希望在MVC中引入更多模型。您通常不應該從其他控制器調用代碼。 – 2013-04-09 15:30:20

回答

-1
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
    // Call myMethod 
    SecondController *controller = [[SecondController alloc] init]; 
    [controller myMethod:pt]; 
    [self.navigationController pushViewController:controller animated:YES]; 
    [controller release]; 
} 

-release調用只有在您不使用ARC時才需要。

+0

這是錯誤的。 OP聲明他在故事板中創建了兩個控制器。使用alloc init將創建一個新的實例,而不是在故事板中獲取該實例。 – rdelmar 2013-04-09 15:57:11

1

您可以使用NSNotification或自定義委託。

請通過以下鏈接查看我的答案。

Can't use reloadData from another class

兩個選項都可用它。

+0

謝謝!通知似乎是最好的解決方案。但是,如何傳遞一個參數(CGPoint)(假設我現在的鏈接中有完全相同的通知)? – user2262230 2013-04-09 16:29:02

0

要通過使用NSNotificationCenter CGPoint,你需要使用NSValue:

NSValue *pointValue = [NSValue valueWithCGPoint:myPoint]; 
[[NSNotificationCenter defaultCenter] postNotificationName:@"updateLeftTable" object:pointValue]; 

在你checkRes:方法,你可以用通過NSNotification的對象屬性獲得點:

相關問題