如何在Objective-C中扩展协议/委托 [英] How to extend protocols / delegates in Objective-C

查看:242
本文介绍了如何在Objective-C中扩展协议/委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想扩展像AVAudioPlayer这样的类,那么最好的方法是向AVAudioPlayerDelegate添加另一个方法吗?我是否为它做了一个类别,我是否扩展它?如果我扩展它,那么我还必须确保覆盖实际的委托getter / setter吗?我该如何扩展协议?以下给出了我的错误

If i want to extend a class like AVAudioPlayer, whats the best way to also add another method to AVAudioPlayerDelegate ?. Do I make a category for it, do I extend it? If I extend it do I then also have to make sure to overwrite the actual delegate getter/setter ? How would I extend the protocol ? The following gives me errors



@protocol AudioTrackDelegate : AVAudioPlayerDelegate {
    - (void)foo;
}
@end

@interface AudioTrack : AVAudioPlayer {
}
@end


推荐答案

创建实现其他协议的协议的语法如下:

The syntax for creating a protocol that implements another protocol is as such:

@protocol NewProtocol <OldProtocol>
- (void)foo;
@end

如果你想在 NewProtocol中调用方法在类型为 OldProtocol 的指针上,您可以调用 respondsToSelector

If you want to call a method in NewProtocol on a pointer typed as OldProtocol you can either call respondsToSelector:

if ([object respondsToSelector:@selector(foo)])
    [(id)object foo];

或者将存根方法定义为 NSObject :

Or define stub methods as a category on NSObject:

@interface NSObject (NewProtocol)
- (void)foo;
@end
@implementation NSObject (NewProtocol)
- (void)foo
{
}
@end

这篇关于如何在Objective-C中扩展协议/委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆