Search code examples
iosiphoneobjective-cios7automatic-ref-counting

ARC and Objective C Subclassing


I am quite new to Obj C and iOS development and I have come across an issue to which I have no understanding why it is happening.

So to set the scene, I have 2 model classes, Player and Computer Player and a Controller.

Player:

@interface Player : NSObject
-(void) playerMessage;
@end

ComputerPlayer:

@interface ComputerPlayer : Player
-(void) computerPlayerOnlyMessage;
@end

Controller:

@interface viewController : UIViewController{
Player *p1;
Player *p2;
Player *currentPlayer;
}


@implmentation ViewController
-(void)viewDidLoad
{
 p1 = [[Player alloc]init];
 p2 = [[ComputerPlayer alloc]init];

 [p1 playerMessage];
 currentPlayer = p2;
 [currentPlayer computerPlayerOnlyMessage];
}

However the issue with the above is [currentPlayer computerPlayerOnlyMessage] gives a complier error when ARC is turned on. When ARC is turned off it gives a compiler warning but will run as I would expect it too.

Any help is appreciated to get help me figure why this behaviour is happening.


Solution

  • Isn't it better to define:

    - (void)playerMessage;
    

    method in ComputerPlayer class and:

    -(void)playerMessage {
       [super playerMessage];
       
       [self computerOnlyPlayerMessage];
    
    }
    

    That's a point of inheritance, isn't it? You defined (expecting) your class variable as Player but NOT ComputerPlayer, and if it is ComputerPlayer it will execute specific work only for "computer".

    Of course then you execute:

    [Player playerMessage]; // Warning should gone