本文介绍了Obj-C错误:预期的标识符或'('的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用按钮,计分器和计时器制作一个简单的应用程序,但出现一些错误

I'm trying to make a simple app with a button a score counter and a timer but I'm getting some errors

    #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

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

If I add ';' I get this instead:

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

我该怎么办?

推荐答案

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

You are mixing up interface and implementation. The interface containsthe (globally visible) instance variables, properties and method declarations, i.e.the prototypes:

@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.
  • 为销售点创建属性(如果尚未创建):

  • The convention is to start class names with a capital letter: XyzViewController.
  • Create properties for the outlets (if you don't have them already):

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

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

The compiler synthesizes the instance variable _scoreLabel automatically, so you don't need it in the interface. And then access the property via

self.scoreLabel.text = ....;

这篇关于Obj-C错误:预期的标识符或'('的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 06:15