2011-04-14 221 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

相關問題