Obj-C中的错误:预期的标识符或'('

时间:2013-11-12 18:56:17

标签: objective-c

我正在尝试制作一个带分数计数器和计时器按钮的简单应用程序,但我收到了一些错误

    #import <UIKit/UIKit.h>

@interface xyzViewController : UIViewController
{
IBOutlet UILabel *scoreLabel;
IBOutlet UILabel *timerLabel;
NSInteger count;
NSInteger seconds;
NSTimer *timer;
}
- (IBAction)buttonPressed  //Expected ';' after method prototype
{
count++
scoreLabel.text = [NSString stringWithFormat:@"Score \n %i", count]
}
@end

如果我添加';'我得到了这个:

- (IBAction)buttonPressed;
{                        //Expected identifier or '('
count++
scoreLabel.text = [NSString stringWithFormat:@"Score \n %i", count]
}
@end

我必须做什么?

3 个答案:

答案 0 :(得分:2)

在.h中定义您的界面,如果它们是公开的,那么在.m中创建您的实现。你不能将它们组合在.h

答案 1 :(得分:2)

您正在混淆interfaceimplementation。界面包含 (全局可见)实例变量,属性和方法声明,即 原型:

@interface xyzViewController : UIViewController
{
    IBOutlet UILabel *scoreLabel;
    IBOutlet UILabel *timerLabel;
    NSInteger count;
    NSInteger seconds;
    NSTimer *timer;
}
- (IBAction)buttonPressed;

@end

该方法本身进入实施:

@implementation xyzViewController

- (IBAction)buttonPressed
{
    count++;
    scoreLabel.text = [NSString stringWithFormat:@"Score \n %i", count];
}
@end

说明:

  • 惯例是使用大写字母XyzViewController启动类名。
  • 为网点创建属性(如果您还没有):

    @property (weak, nonatomic) IBOutlet UILabel *scoreLabel;
    

    编译器自动合成实例变量_scoreLabel,因此您不需要在界面中使用它。然后通过

    访问该物业
    self.scoreLabel.text = ....;
    

答案 2 :(得分:1)

你想在函数内部使用分号:

- (IBAction)buttonPressed {
count++;
scoreLabel.text = [NSString stringWithFormat:@"Score \n %i", count];
}

这是要使用的正确语法。