-1

I'm following this tutorial. And I keep getting this casting error. I've imported the Obstacle.h file in the shown class (MainScene.m). I have no idea what I'm doing wrong

 - (void)spawnNewObstacle {
     CCNode *previousObstacle = [_obstacles lastObject];
     CGFloat previousObstacleXPosition = previousObstacle.position.x;

     if (!previousObstacle) {
         // this is the first obstacle
         previousObstacleXPosition = firstObstaclePosition;
     }

     Obstacle *obstacle = (Obstacle *)[CCBReader load:@"Obstacle"];
     obstacle.position = ccp(previousObstacleXPosition + distanceBetweenObstacles, 0);
     [obstacle setUpRandomPosition];
     [_physicsNode addChild:obstacle];
     [_obstacles addObject:obstacle];
 }

Error:

-[CCNode setUpRandomPosition]: unrecognized selector sent to instance 0x9a88a30
2014-04-20 10:51:28.046 FlappyFlyl[2104:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CCNode setUpRandomPosition]: unrecognized selector sent to instance 0x9a88a30'
Pawan Rai
  • 3,434
  • 4
  • 32
  • 42
stumped
  • 3,235
  • 7
  • 43
  • 76
  • 4
    What makes you think that casting changes the class of an object?? All it does is tell the compiler to consider the type to be the one specified. – Hot Licks Apr 20 '14 at 15:01
  • afaik obstacle is the first child of the node returned by ccbreader load – CodeSmile Apr 20 '14 at 15:47
  • Sorry, I haven't programmed in a while and I've forgotten a lot of these concepts. What would you suggest I do to fix it? The example runs fine with the same code – stumped Apr 20 '14 at 15:49
  • write a correct CCNode class that has the code you expect it to have – Daij-Djan Apr 20 '14 at 17:22
  • @LearnCocos2D that is only the case for `loadAsScene`. A regular `load` should return the SpriteBuilder root node. – Ben-G Apr 20 '14 at 22:37

2 Answers2

1

Likely you didn't set the custom class of your root node in "Obstacle.ccb" in SpriteBuilder correctly. That's why your "Obstacle.ccb" root node is a CCNode and not an Obstacle object.

Ben-G
  • 4,996
  • 27
  • 33
0

The obstacle variable does not hold an object of type Obstacle. Instead it holds an object of type CCNode. CCNode does not have a method named -setUpRandomPosition, so you get a runtime error. In Objective-C, casting is a no-op. It doesn't do anything except helping the reader of your code see the intent of the person who wrote the code.

In this regard Objective-C differs from languages like C++ or Java. Objective-C has an object system that is similar to the programming language "Smalltalk".

Michael
  • 6,451
  • 5
  • 31
  • 53