我有一个访问我的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