我是Obj-C的新手,如果问题很明显,我很抱歉!
无论如何,我只是进入objective-c,并试图创建一个基本的iOS计数器,每次用户单击/触摸UI时,都会增加一个点计数器。
我已经创建了currentScore int,可以将其记录到控制台。我还成功地将UI的每次触摸记录到控制台。
我现在要做的是,在每次触摸时访问currentScore int,并将int递增1。
正如我所说,可能很容易,但不能100%确定如何在其他函数中引用其他变量!
提前谢谢。
//
// JPMyScene.m
//
#import "JPMyScene.h"
@implementation JPMyScene
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
/* Setup your scene here */
self.backgroundColor = [UIColor redColor];
//Initiate a integer point counter, at 0.
int currentScore = 0;
NSLog(@"Your score is: %d", currentScore);
}
return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
for (UITouch *touch in touches) {
NSLog(@"Tap, tap, tap");
//TODO: For each tap, increment currentScore int by 1
}
}
-(void)update:(CFTimeInterval)currentTime {
/* Called before each frame is rendered */
}
@end
首先在interface.h接口中将整数声明为全局变量或属性。然后从任意位置进行访问和修改。这是您的界面和实现:
@interface JPMyScene
{
int currentScore;
}
@end
@implementation JPMyScene
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
self.backgroundColor = [UIColor redColor];
currentScore = 0;
NSLog(@"Your score is: %d", currentScore);
}
return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
for (UITouch *touch in touches) {
NSLog(@"Tap, tap, tap");
currentScore++;
}
}
-(void)update:(CFTimeInterval)currentTime {
}
您的问题与ObjC无关,而是与OOP有关。基本上,您需要一个在对象的多个方法中可用的变量。解决方案是将currentScore声明为JPMyScene的实例变量。
将currentScore变量更改为全局变量,如本代码所示。
//
// JPMyScene.m
//
#import "JPMyScene.h"
@implementation JPMyScene
int currentScore = 0;
-(id)initWithSize:(CGSize)size {
/* Setup your scene here */
self.view.backgroundColor = [UIColor redColor];
//Initiate a integer point counter, at 0.
NSLog(@"Your score is: %d", currentScore);
return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
for (UITouch *touch in touches) {
NSLog(@"Tap, tap, tap");
currentScore++;
NSLog(@"Your score is: %d", currentScore);
//TODO: For each tap, increment currentScore int by 1
}
}
-(void)update:(CFTimeInterval)currentTime {
/* Called before each frame is rendered */
}
@end