我是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
答案 0 :(得分:1)
首先在接口.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 {
}
答案 1 :(得分:0)
您的问题与ObjC无关,但与OOP有关。基本上,您需要一个在对象的多个方法中可用的变量。解决方案是将currentScore声明为JPMyScene的实例变量。
答案 2 :(得分:-2)
将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