2012-01-08 43 views
0

我剛開始學習Objective-C,有一件事對我來說並不明確將void連接到操作?

好吧,我在InterFace Builder中有一個按鈕。我的.h文件我有代碼;

- (void)startButtonPressed:(id)sender; 

我怎麼能'link''void'我的按鈕做的動作?

這裏的代碼不能正常工作我該怎麼做?

- (void)startButtonPressed:(id)sender { 

//Some stuff in here 

    } 

有誰知道如何解決這個問題?

回答

1

IBAction,其實是void

http://www.cocoadev.com/index.pl?IBAction

// from <AppKit/NSNibDeclarations.h> 
#ifndef IBAction 
    #define IBAction void 
#endif 

它被賦予這樣,你就不會弄亂行動從UI和您的類實現的功能來。

要創建功能連接與UI,你需要將它的類型設置爲IBAction

// .h 
- (IBAction)startButtonPressed:(id)sender; 
// .m 
- (IBAction)startButtonPressed:(id)sender { 
    //Some stuff in here 
} 

這是coorect,以及

// .m 
- (void)startButtonPressed:(id)sender { 
    //Some stuff in here 
} 

實施的類型,可以void直接

+0

我做過; ' - (IBAction)startButtonPressed:(id)sender;'但我無法將按鈕連接到動作?在界面生成器? – Blazer 2012-01-08 21:22:32

+0

表示您看到IB中的操作,無法連接,或者您甚至沒有看到它? – 2012-01-08 21:25:32

1

界面生成器需要具有標記IBAction方法:

- (IBAction)startButtonPressed:(id)sender; 
+0

Interface Builder需要使用'IBAction'標記接口,而不是實現。 – 2012-01-08 20:47:08

+0

@JasonCoco感謝您的糾正。我通常都會標記 - 我不知道只標記'.h'就足夠了。 – dasblinkenlight 2012-01-08 20:48:58

+0

Jason。 - 這不再是真的...... – bbum 2012-01-08 20:49:19

2

變化在頭文件(.H文件)IBAction代替void返回值。所以,他們應該是這樣的:

// .h header file 
- (IBAction)startButtonPressed:(id)sender; 

// .m implementation file 
- (void)startButtonPressed:(id)sender { /* do some work */ } 

IBAction類型是完全一樣的編譯器爲void。 Interface Builder使用它來分析頭文件以查看它可以鏈接的內容。當您將返回類型設置爲IBAction時,您告訴界面構建器可以將操作鏈接到此方法實現(現在您可以在IB中繪製連接)。

由於voidIBAction是相同的,您可以在您的實現文件中使用IBAction以及返回類型,雖然這不常用。此外,由於IBActionvoid是相同的,因此只能創建不返回任何值的操作(即,操作方法的返回必須爲void)。