2016-09-23 96 views
-1

我有一个叫做Card的类和一个叫做PlayingCardCard的子类。 在ViewController中,我有一个将Card作为参数的方法。对象铸造目标-c

喜欢的东西:

- (void)doSomething: (Card *) card 
{ 
    card = (PlayingCard *)card; 
    NSString *aProperty = card.aPropertyOfPlayingCard; // complained 
    // ... 
} 

我已经投了cardPlayingCard。为什么Xcode中抱怨说:

回答

3

变量card只能进行一次申报“房产证*‘“aPropertyOfPlayingCard没有对象类型中发现’”。在您的代码中card作为方法的参数传递。即使通过类型转换为其类指定任何其他对象,该变量也会被解释为最初声明的类型的变量。您可以创建PlayingCard类型的新变量,并使用强制类型转换的实例card分配给它:

- (void)doSomething: (Card *) card 
{ 
    PlayingCard *playingCard = (PlayingCard *)card; 
    NSString *aProperty = playingCard.aPropertyOfPlayingCard; 
    //... 
} 

编辑

但是你应该知道,该实例传递到作为card可以不同的东西的方法比类实例PlayingCard什么意思它可能不实现一个getter aPropertyOfPlayingCard。在这种情况下,调用aProperty将导致抛出异常“发送到实例0x ...的无法识别的选择器”。您可能想要添加测试:

if([card isKindOfClass:[PlayingCard class]]) { 
    PlayingCard *playingCard = (PlayingCard *)card; 
    NSString *aProperty = playingCard.aPropertyOfPlayingCard; 
} 
+1

“在这种情况下aProperty可能为零”是错误的。在这种情况下,您会收到一个异常“发送给实例的无法识别的选择器...”。 – Willeke

+0

@Willeke你是对的。我错误地调用了一个无对象的方法,(这将是有效的)。这是不同的,因为“aProperty”可能是一个现有的对象。 – Greg