2015-04-03 61 views
0

对于Obj-C,我很新,所以如果问题相当明显,我们很抱歉!从另一个方法引用一个变量objective-c

无论如何,我只是进入objective-c并尝试创建一个基本的iOS计数器,每次用户点击/触摸UI时,点计数器都会增加。

我已经创建了currentScore int并可以将其记录到控制台。我还将每次触摸的UI都成功记录到控制台。

什么我现在试图做的是,用1

正如我说的,可能很容易访问每个触摸currentScore int和递增int,但不能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 

回答

-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 
+0

全局变量?请不要将这样的东西教给面向对象的初学者,事情可能很容易脱离他们的手。顺便说一句,静态的会有同样的效果,但没有讨厌的“全局性”。 – Cristik 2015-04-14 18:20:22

0

您的问题与ObjC无关,但与一般的OOP无关。基本上你需要一个对象的多个方法中可用的变量。解决方案是将currentScore声明为JPMyScene的实例变量。

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 { 

} 
相关问题