如何定义将方法添加到实现特定协议的类的类别? [英] How do I define a category that adds methods to classes which implement a particular protocol?

查看:46
本文介绍了如何定义将方法添加到实现特定协议的类的类别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向实现 SOManagedObject 协议的 NSManagedObject 的子类添加一些方法.我试过这样定义它:

I want to add some methods to subclasses of NSManagedObject that implement the SOManagedObject protocol. I've tried defining it like this:

@interface NSManagedObject <SOManagedObject> (MyExtensionMethods)
    ...
@end

...但这似乎无效.如何定义将方法添加到实现特定协议的类的类别?

...but that doesn't seem to be valid. How do I define a category that adds methods to classes which implement a particular protocol?

推荐答案

一般来说,在所有此类类上定义此类类别并非易事.但您的实际问题似乎更简单:如何将类别方法添加到 NSManagedObject 以仅用于实现 的子类?这是可以解决的.

Defining such a category on all such classes in general is not easily solvable. But your actual problem seems simpler: How does one add a category method to NSManagedObject for use only with subclasses that implement <SOManagedObject>? This is solvable.

您要做的是将方法添加到 NSManagedObject,然后检查您正在使用的实例是否可以处理您要从 <发送的消息/代码>.

What you want to do is add the method to NSManagedObject, then check that the instance you're working with can handle the messages you want to send it from <SOManagedObject>.

假设我们得到了:

/* SOManagedObject.h */
@protocol SOManagedObject
- (void)frobble_so;
- (void)bobble_so;
@end

现在让我们为所有实现 SOManagedObjectNSManagedObject 子类添加一个类别方法:

Now let's add a category method to all NSManagedObject subclasses that implement SOManagedObject:

/* NSManagedObject+SOConvenience.h */
@interface NSManagedObject (SOConvience)
/* Frobbles and bobbles - no effect on non-<SOManagedObject>-conforming
 * instances. */
- (void)frobbleAndBobble_so;
@end

为此,我们实现如下方法:

To do so, we implement the method like so:

/* NSManagedObject+SOConvenience.m */
@implementation NSManagedObject (SOConvenience)
- (void)frobbleAndBobble_so
{
    if (![self conformsToProtocol:@protocol(SOManagedObject)]) return;

    NSLog(@"%s: Thunderbirds are GO! Let's frobble and bobble!", __func__);
    [self frobble_so];
    [self bobble_so];
}
@end

您可以选择断言以确保您没有将方法发送到错误的对象,或者您可以使用 respondsToSelector: 而不是检查协议一致性.无论你的船漂浮在什么地方,但这种通用的方法应该带你去你想去的地方.

You could optionally assert to ensure you are not sending the method to the wrong objects, or you could use respondsToSelector: instead of checking for protocol conformance. Whatever floats your boat, but this general tack should take you where you want to go.

这篇关于如何定义将方法添加到实现特定协议的类的类别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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