2012-01-08 129 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)。