hariszaman hariszaman - 3 months ago 25
Objective-C Question

Check for id class type without code duplication

I have to two classes which provide different functions I need to detect the class of each of it and then perform those function that results in code duplication. Is there a way to specify id ?

@property (nonatomic, retain) id player;
-(void) checkPlayer
{
if ([self.player isKindOfClass:[MPMoviePlayerController class]]){
MPMoviePlayerController* player = (MPMoviePlayerController*) self.player;
if (player.loadState != MPMovieLoadStateStalled || player.loadState != MPMovieLoadStateStalled)
{
// do something
}
}
else if([self.player isKindOfClass:[MyCustomPlayerController class]]) {
MyCustomController* player = (MyCustomPlayerController*) self.player;
if (player.loadState != MPMovieLoadStateStalled || player.loadState != MPMovieLoadStateStalled)
{
// do something else
}
}
}

Answer

It would be better to use protocols for that case. You code will be nice and clean.

Example:

@protocol Player
- (StateEnum)state;
@end

@interface MyCustomPlayerController <Player>
@end

@interface MPMoviePlayerController <Player>
@end


@property (nonatomic, retain) id<Player> player;
-(void) checkPlayer {
   if (self.player.state != MPMovieLoadStateStalled || self.player.state != MPMovieLoadStateStalled)
   }
}