Cocos2d iphone 将变量从一个场景传递到另一个场景-Cocos2D

Cocos2d iphone 将变量从一个场景传递到另一个场景-Cocos2D,cocos2d-iphone,Cocos2d Iphone,我在游戏中有一个关卡场景,我在其中选择关卡。在这个场景中,我将显示在CCLabelTTF中选择的级别。现在我想把这个标签上显示的值传递给我的主场景。我的做法如下: HelloWorld *hello=[HelloWorld getInstance]; //HelloWorld is main scene hello.strLevel=[lblLevel string]; //strLevel is NSString to which I am passing the label tex

我在游戏中有一个关卡场景,我在其中选择关卡。在这个场景中,我将显示在CCLabelTTF中选择的级别。现在我想把这个标签上显示的值传递给我的主场景。我的做法如下:

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()。为什么不呢。但是,当控件返回到我传递值的行的级别场景时,什么也不会发生,HelloWorld显示strLevel的值null

我知道单例传递值比AppDelegate更好。但我不能这样做。有人能纠正我吗

谢谢使用singleton。这是一个关于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]];
要传递到ReplaceSecene的HelloWorld实例与 HelloWorld*您好,您将单例实例传递给了。这就是它没有strLevel值的原因。strLevel值放在HelloWorld单例中。试一试

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

谢谢这些讨论真的很棒。但我的问题在于在其他场景中使用singleton。使用singleton并不能帮助我在两个场景之间共享价值。我知道我在某个地方错了,但不知道哪里错了。你可以从程序中的任何地方调用你的singleton对象,因为它是静态的,就像这个[[MySingleton sharedInstance]myMethod];sharedInstance是一个类函数,类似于+(MySingleton*)sharedInstance,它将ptr返回给静态分配的MySingleton*类对象。myMethod是一个实例方法。诀窍在于,单身汉会一直生活到节目结束。除非你认为有必要,否则你不应该发布它。此外,您不必alloc/init您的单例,因为它在sharedInstance调用中只执行一次。CCDirector也是个单身汉。我不会把我的场景定义为歌手,因为场景变化很快。你会被所有的场景都留在记忆中。而是构建一个存储数据的sharedData类。我想这就是你的问题所在[[CCDirector sharedDirector]replaceSecene:[HelloWorld node];因为调用节点实际上返回了HelloWorld场景的一个新的自动删除实例。非常感谢KakoSquid:)我真的很成功。您关于创建独立数据类的观点非常有用。