cocos2d中的单例类。访问变量

时间:2012-01-07 21:35:15

标签: iphone objective-c ios cocos2d-iphone

访问Singleton Class的属性时遇到问题。 我写了这段代码:Singleton.h -

#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有错误的价值。请帮我找错。

1 个答案:

答案 0 :(得分:3)

也许试试:

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

    return _sharedSingleton;
  }
  return nil;
}