2013-05-02 33 views
0

我是新的Objective-C,我有一個問題。我不明白我的錯誤在哪裏。Objective-C訪問另一個類的計數器

櫃檯告訴我,該值是0

我有一個遊戲類最多的時間,這裏是一個計數器。一段時間後,遊戲停止屏幕切換到End類。而在最後一堂課,我想打印出分數。但它不起作用。

Game.h  
@interface Game : CCLayer 
{ 
    int counter; 
}  
@property (readwrite, nonatomic) int counter;  
+(int)returnCounter;  
@end 
Game.m  
@implementation Game  
@synthesize counter;  
-(void)methodForMyCounter{ 
    counter++; 
} 
    +(int)returnCounter{ 
return counter; 
} 
End.h  
End.m  
@implementation  
-(void)getCounter{ 
    //here i want to print out the counter  
} 
+0

獲取一個指向其他類的實例的指針。使用它來訪問計數器屬性。 – 2013-05-02 15:03:47

回答

0

用 - (int)returnCounter替換+(int)returnCounter並從您的實例中調用returnCounter方法!

Game.h 

@interface Game : CCLayer 
{ 
    int counter; 
} 

@property (nonatomic, assign) int counter; 

-(int)returnCounter; 

@end 


Game.m 

@implementation Game 

@synthesize counter; 

-(void)methodForMyCounter{ 
    counter += 1; 
} 

-(int)returnCounter{ 
return counter; 
} 



End.h 
@interface End : NSObject 
{ 
    Game *_game; 
} 

End.m 

@implementation 

-(int)getCounter{ 
    if(!_game) { 
    _game = [[Game alloc] init]; 
    //[_game retain] //if your are not using ARC 
    } 
    NSLog(@"%s %d or %d", __FUNCTION__, [_game returnCounter], _game.counter) 
    return [_game returnCounter]; 

} 
1

counterGame類的一個實例的屬性,讓你無論是需要能夠訪問該實例,或移動櫃檯那就是無論是GameEnd對象訪問的位置。我會做後者。

counter移動到您的應用程序代理和@synthesize它。然後你可以在任何你想要的地方使用它:

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 
int counterValue = [appDelegate counter];