2010-01-27 69 views
1

我只是想構建一個簡單的委託,它編譯成功,但它似乎沒有做任何事情。 請檢查我的代碼下面,FirstViewContoller和SecondViewController都有單獨的xib文件,SecondViewController有一個按鈕連接到myMethod當然。爲什麼我的自定義iPhone代理不工作?

我一直在學習圍繞目標c和iPhone SDK幾個月的方式,我一直在使用一本書和lynda.com教程來幫助,實際上我使用xcode模板複製了大部分代碼一個實用程序的應用程序,我相信我明白這裏發生了什麼,但是有一些我錯過了,因爲按鈕沒有響應。

如果您需要更多信息,請詢問。

非常感謝, 克里斯

SecondViewController.h

#import <UIKit/UIKit.h> 

@protocol SecondViewControllerDelegate; 


@interface SecondViewController : UIViewController { 
    id <SecondViewControllerDelegate> delegate; 
} 

@property (nonatomic, assign) id <SecondViewControllerDelegate> delegate; 


-(IBAction) myMethod; 

@end 

@protocol SecondViewControllerDelegate 

-(void)viewControllerDidFinish:(SecondViewController *)controller; 

@end 

SecondViewController.m

@implementation SecondViewController 

@synthesize delegate; 

-(IBAction) myMethod 
{ 
    [self.delegate viewControllerDidFinish:self]; 
} 
// 
@end 

FirstViewController.h

@interface FirstViewController : UIViewController <SecondViewControllerDelegate>{ 
// 
@end 

FirstViewController.m

@implementation FirstViewController 

-(void)viewControllerDidFinish:(SecondViewControllerDelegate *)controller 
{ 
    NSLog(@"delegate is being used"); 
} 
// 
@end 

編輯 - 這是一個老的文章,但只是爲了澄清,我只是忘了分配SecondViewController代表在FirstViewController

+1

我沒有看到你指派的SecondViewController的委託屬性,你必須在創建時做到這一點?發送消息給零是合法的... – 2010-01-27 23:09:37

+0

你能舉個例子嗎?這可能是缺少的東西 – Chris 2010-01-27 23:44:24

+0

好吧,我明白了,非常感謝。分配代理屬性是有道理的,我在查看Utility模板時忽略了這部分,因爲我沒有做任何翻轉視圖工作。我現在明白宣佈代表是不夠的,感激它! – Chris 2010-01-27 23:49:05

回答

1

如何分配SecondViewController的委託屬性? 這是我失蹤的最後一部分...

0

兩件事情:

  1. 你IBAction方法myMethod,如果它真的是一個IBAction,需要參數: -(IBAction)myMethod:(id)sender 在你責怪d elegate模式,確保myMethod被調用(設置斷點並查看)。

  2. 你的委託方法似乎被聲明爲一個委託類型作爲參數,而不是你想要傳遞到那裏的viewController。這可能都被id類型所掩蓋,但我想你可能想要重新聲明這些聲明。

+0

感謝您的回覆本,它並沒有幫助,雖然 1 - 如果我嘗試添加一個IBaction方法的發件人參數我得到一個錯誤在IB和應用程序崩潰 2 - 這是一個錯字時,將代碼這個問題,我已經修改了上述內容,但情況並非如此。 還有什麼可以的嗎? – Chris 2010-01-27 23:41:53

+0

再次感謝Ben,亞當的建議幫助,請忽略。感謝您指出我的爛攤子! – Chris 2010-01-27 23:49:49

+0

作記錄, - (IBAction)respondToButtonClick; - (IBAction)respondToButtonClick:(id)sender; (IBAction)respondToButtonClick:(id)sender forEvent:(UIEvent *)event; 根據http://developer.apple.com/mac/library/documentation/DeveloperTools/Conceptual/IB_UserGuide/CodeIntegration/CodeIntegration.html 是否所有有效的IBActions如果您更改IBAction的類型,我認爲您必須重新連接IB中的連接,否則它會嘗試發送錯誤的選擇器 – 2010-01-28 00:31:58

相關問題