2015-04-03 81 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 { 

} 
相關問題