Adnan Zahid
Adnan Zahid

Reputation: 583

Unrecognized selector sent to instance error?

Consider this code:

SCNNode *someNode = [[SCNNode alloc] init];
Piece *piece = (Piece *)someNode;
[piece pick];

Where Piece is a sub-class of SCNNode and contains a method called pick. Xcode is returning this error:

[SCNNode pick]: unrecognized selector sent to instance

Can someone tell what is wrong with my code?

Edit:

I tried this as well. Same problem.

- (id)initPieceWithNode:(SCNNode *)node {

    if (self = [super init]) {
         self = (Piece *)[node copy];
    }

return self;
}

Upvotes: 0

Views: 291

Answers (3)

David Ansermot
David Ansermot

Reputation: 6112

Here you're casting a SCNNode into a Piece, you're not creating a Piece object. If you convert, the method won't appear magically in a SCNNode.

You should do something like :

Piece *piece = [Piece pieceWithNode:someNode];

And exemple :

+ (Piece *)pieceWithNode:(SCNNode *)aNode {
     Piece *newPiece = [Piece new];

     newPiece.property1 = aNode.propertyX
     newPiece.property2 = aNode.propertyY
     ...

     return newPiece;
}

This is the best way to do that.

EDIT 2 : According to comments :

Piece *piece = [Piece new]; 
[piece pick];

It's enougth

Upvotes: 1

mnuages
mnuages

Reputation: 13462

if Piece is a subclass of SCNNode then

   Piece *piece = [[Piece alloc] init];
   [piece pick];

Upvotes: 1

trojanfoe
trojanfoe

Reputation: 122449

If you are handling a polymorphic type then you should query the exact type of the object and perform actions upon that object that are appropriate for that type.

For example you have:

@interface SCNNode : NSObject
- (void)baseMethod;
@end

@interface Piece : SCNNode
- (void)derivedMethod;
@end

Then the handling code should behave something like this:

- (void)doSomethingWithNode:(SCNNode *)node
{
    [node baseMethod];
    if ([node isKindOfClass:[Piece class]]) {
        [node derivedMethod];
    }
}

It is not appropriate for the handling code to convert the base type to a derived type as I doubt it's in a position to provide the additional attributes of the object. If you are converting then something is wrong elsewhere.

Upvotes: 0

Related Questions