测试如果对象是否为零

时间:2014-04-12 09:38:23

标签: objective-c sprite-kit

-(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 个答案:

答案 0 :(得分:1)

用于检查mainGameScene是否已初始化,因为如果presentScene,则nil不能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

你现在拥有的代码是无用的,因为它试图用对象做一些事情,但是没有初始化。
就我而言,你的{{1}}不会被重新初始化,一旦它被引入。