2011-04-14 205 views
1

我在我的游戏中有一个关卡场景,我在其中选择关卡。在这个场景中,我显示了在CCLabelTTF中选择的关卡。现在我想将此标签上显示的值传递给我的主场景。我这样做如下:将变量从一个场景传递到其他场景 - Cocos2D

HelloWorld *hello=[HelloWorld getInstance]; //HelloWorld is main scene 

hello.strLevel=[lblLevel string]; //strLevel is NSString to which I am passing the label text 

[[CCDirector sharedDirector]replaceScene:[HelloWorld node]]; 

在我的HelloWorld场景中,我使用singleton共享Level场景中使用的标签的值。

//HelloWorld.h 


@interface HelloWorld : CCColorLayer 

{ 

NSString *strLevel; 

} 

@property(nonAtomic,retain)NSString *strLevel; 

+(HelloWorld*)getInstance; 

HelloWorld.mm 

@implementation HelloWorld 

@synthesize strLevel; 

static HelloWorld *instance=nil; 

__________________________ 

//Some code 

__________________________ 


+(HelloWorld*)getInstance 

{ 

if(instance==nil) 

{ 

instance=[HelloWorld new]; 

} 

return instance; 

} 

然而,由于控制达到

instance=[HelloWorld new]; 

的init()被调用,这不是working.As很快。那么为何不。但是,当控件返回到传递值的行处的Level场景时,没有任何反应,并且HelloWorld显示strLevel的值为null。

我知道singleton是比AppDelegate传递值更好的方法。但我无法这样做。有人能纠正我吗?

谢谢

回答

2

使用单身。 What should my Objective-C singleton look like?这是关于obj-c中单例的一个很好的讨论。好运

[编辑]

HelloWorld *hello=[HelloWorld getInstance]; //HelloWorld is main scene 
hello.strLevel=[lblLevel string]; //strLevel is NSString to which I am passing the label text 
[[CCDirector sharedDirector]replaceScene:[HelloWorld node]]; 

,你传递给replaceScene的HelloWorld的实例并不像 了HelloWorld *你好,你通过单实例相同。这就是为什么没有strLevel值的原因。尽管strLevel值放置在HelloWorld单例中。尝试

NSLog(@"%@",[[HelloWorld getInstance] strLevel]); //somewhere in the code 
+0

谢谢。这些都是非常棒的讨论。但我的问题在于在其他场景中使用单身。使用单身人士不会帮助我在两个场景之间分享价值。我知道我错了,但不知道在哪里。 – Nitish 2011-04-14 06:13:04

+0

你可以从程序中的任何地方调用你的单例对象,因为它是静态的,就像这样[[MySingleton sharedInstance] myMethod]; sharedInstance是一个类函数,看起来像这样+(MySingleton *)sharedInstance,它返回一个ptr到静态分配的类MySingleton *的对象。 myMethod是一个实例方法。诀窍是单身人士一直活到终止程序。除非你认为必要,否则你不应该释放它。你也不必分配/初始化你的单例,因为它只在sharedInstance调用中完成一次。 CCDirector也是单身人士。 – 2011-04-14 06:25:51

+0

我不会将我的场景定义为singelton,因为场景变化很快。你会被困在内存中的所有场景。而是在您存储数据的地方构建一个sharedData类。我认为这是你的问题所在[[CCDirector sharedDirector] replaceScene:[HelloWorld node]];因为调用节点实际上是返回HelloWorld场景的一个新的自动释放实例。 – 2011-04-14 06:38:13