2012-01-07 61 views
1

我有一個訪問我的Singleton類屬性的問題。 我已經寫了這個代碼:Singleton.h -cocos2d中的單例類。訪問變量

#import <Foundation/Foundation.h> 

@interface Singleton : NSObject{ 
    int _wordNumber; 
} 
+ (Singleton *) sharedSingleron; 
@property (readwrite) int wordNumber; 
@end 

Singleton.m文件 -

#import "Singleton.h" 
@implementation Singleton 
@synthesize wordNumber = _wordNumber; 


static Singleton* _sharedSingleton = nil; 

+(Singleton *) sharedSingleron{ 
    @synchronized([Singleton class]) 
    { 
     if (!_sharedSingleton) 
      [[self alloc] init]; 

     return _sharedSingleton; 
    } 

    return nil; 
} 
+(id)alloc 
{ 
    @synchronized([Singleton class]) 
    { 
     NSAssert(_sharedSingleton == nil, @"Attempted to allocate a second instance of a singleton."); 
     _sharedSingleton = [super alloc]; 
     return _sharedSingleton; 
    } 

    return nil; 
} 

-(id)init { 
    self = [super init]; 
    if (self != nil) { 

    } 

    return self; 
} 


@end 

在我的第一個場景我設置wordNumber並轉到另一個場景

[Singleton sharedSingleron].wordNumber = wordNum; 
[[CCDirector sharedDirector] replaceScene: [CCTransitionFlipAngular transitionWithDuration:0.3 scene:[WordsLayer node]]]; 

並在WordsLayer.m我試圖得到這個屬性

-(id) init 
{ 
    if((self=[super init])) { 

     int wordNum = [Singleton sharedSingleron].wordNumber; 

    } 
    return self; 
} 

但wordNum有錯誤的值。請幫助我找到一個錯誤。

+0

嘗試添加到性能的實現(單班)的NSLog當前值。我認爲它可以幫助你。 – OdNairy 2012-01-07 21:40:52

+1

你從未設置_sharedSingleton .... – 2012-01-08 03:01:28

回答

3

也許嘗試:

+(Singleton *) sharedSingleron{ 
    @synchronized([Singleton class]) { 
    if (!_sharedSingleton) 
     _sharedSingleton = [[self alloc] init]; 

    return _sharedSingleton; 
    } 
    return nil; 
} 
+0

它沒有幫助。當我嘗試在Singleton類中獲得wordNumber時,wordNumber屬性也有不好的值...可能是屬性描述中的問題? – nabiullinas 2012-01-08 08:28:59

+0

哦,這個解決方案是正確的。我發現一個錯誤。 – nabiullinas 2012-01-08 08:40:18

+1

你寫的代碼來自「學習Cocos2D:使用Cocos2D,Box2D和Chipmunk構建IOS遊戲的實踐指南」一書,第7章,第172-175頁。我發現這篇文章是因爲我遇到了同樣的問題。看來這是本書中的一個錯誤。 @YvesLeBorg的解決方案也適用於我。 – Ben 2012-07-13 07:53:03