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

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

问题描述

如果我想扩展像AVAudioPlayer这样的类,最好的方法是同时向AVAudioPlayerDelegate添加另一个方法吗?

If i want to extend a class like AVAudioPlayer, whats the best way to also add another method to AVAudioPlayerDelegate?

我应该为它做一个类别,我可以扩展它吗?

Should I make a category for it, do I extend it?

如果我扩展它,那我还必须确保覆盖实际的委托getter/setter吗?我将如何扩展协议?

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?

以下内容给我错误

@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

如果要在类型为 OldProtocol 的指针上在 NewProtocol 中调用方法,则可以调用 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天全站免登陆