2014-04-12 85 views
1
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ 

UITouch *touch = [touches anyObject]; 
CGPoint location = [touch locationInNode:self]; 
SKNode *node = [self nodeAtPoint:location]; 

if ([node.name isEqualToString:@"play"]){ 

    NSLog(@"play was touched"); 

    SKScene *mainGameScene = [[MainGame alloc] initWithSize:self.size]; 
    if (!mainGameScene){ 
    SKTransition *transition = [SKTransition fadeWithColor:[UIColor blackColor] duration:0.5]; 
    [self.view presentScene:mainGameScene transition:transition]; 
    } 

} 

}測試如果對象是零或不

從我的理解上面的檢查的代碼,如果mainGameScene是零,如果它再通過if語句去。

這樣做有益嗎?還是隻是浪費了代碼?因爲如果多次調用此代碼的方法不會創建新對象SKScene

+1

如果你在'if(!mainGameScene)'之前分配/ init'mainGameScene',那麼......看起來if塊永遠不會是真的,因此不會執行。 – staticVoidMan

+0

如何在alloc/init之前測試一個對象? – Mutch95

回答

1

它用於檢查mainGameScene是否已初始化,因爲如果它是nil,則不能presentScene。 如果你想只檢查對象初始化,然後

SKScene *mainGameScene; 
//creates new variable - place it at the beginning of the code, before @implementation and @interface 
if(mainGameScene){ 
// it is already inited (you have already tapped once), it will be called always, since it is inited at else 
//it is called when you tap the second, the third time, etcetera 
SKTransition *transition = [SKTransition fadeWithColor:[UIColor blackColor] duration:0.5]; 
[self.view presentScene:mainGameScene transition:transition]; 
}else 
{ 
//Calls only once, when you first touching the screen, and initing mainGameScene. 
//It won't be called ANYMORE, since it is inited. 
mainGameScene = [[MainGame alloc] initWithSize:self.size]; 
} 

你現在的代碼是無用的,因爲它試圖做一些與對象,未初始化。
就我而言,你的mainGameScene一旦被引用就不會被重新初始化。

+0

所以如果這被稱爲多次,它不會每次分配一個新的'mainGameScene'? @AlieN – Mutch95

+0

你的init方法被調用,直到你的場景被初始化。如果它已經被初始化,它將不會被再次調用,所以它不會每次都創建一個新的mainGameScene。 – AlieN

+0

我已經更新了代碼,也許你會理解我的意思吧? – Mutch95