我有一個訪問我的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有錯誤的值。請幫助我找到一個錯誤。
嘗試添加到性能的實現(單班)的NSLog當前值。我認爲它可以幫助你。 – OdNairy 2012-01-07 21:40:52
你從未設置_sharedSingleton .... – 2012-01-08 03:01:28