我必须有两个类,它们提供了检测每个类的类所需的不同函数,然后执行那些导致代码重复的函数。有没有办法指定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
}
}
}
答案 0 :(得分:1)
最好在这种情况下使用协议。你的代码会很干净。
示例:
@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)
}
}
答案 1 :(得分:0)
您可以通过创建@protocol
来消除代码重复@protocol LoadStateProtocol <NSObject>
@property (assign, ...) MPMovieLoadState loadState;
@end
并且MyCustomPlayerController和MPMoviePlayerController都符合此协议。
@interface MyCustomPlayerController < LoadStateProtocol >
/* ... */
@end
如果MPMoviePlayerController不是您的类BUT之一已经具有属性loadState,只需在.m文件中创建一个objC类别,该文件具有checkPlayer方法
@interface MPMoviePlayerController (LoadStateProtocol)
< LoadStateProtocol >
@end
@implementation MPMoviePlayerController (LoadStateProtocol)
@end
然后你可以停止检查:
只需将self.player
的类型更改为id< LoadStateProtocol >