在目标C类别中使用超级吗? [英] Using Super in an Objective C Category?

查看:102
本文介绍了在目标C类别中使用超级吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想覆盖我没有源代码的Objective C类中的方法.

我已经研究过了,看来分类应该允许我这样做,但是我想在我的新方法中使用旧方法的结果,并使用super获得旧方法的结果. /p>

每当我尝试这样做时,我的方法都会被调用,但是"super"为nil ...知道为什么吗?我正在使用XCode 2.2 SDK进行iPhone开发.我肯定在使用一个类的实例,并且该类的方法是一个实例方法.

@implementation SampleClass (filePathResolver)
-(NSString*) fullPathFromRelativePath:(NSString*) relPath
{
    NSString *result = [super fullPathFromRelativePath: relPath];

  ... do some stuff with the old result

    return result;
}

注意和说明:从我在Apple Docs中看到的内容,我看来应该允许这样做?

developer.apple.com上的类别文档: 当类别覆盖继承的方法时, 类别可以照常调用 通过消息继承的实现 超级.但是,如果一个类别 覆盖已经存在的方法 存在于类别的类别中 是没有办法调用原始的 实施.

解决方案

category扩展了原始类,但是它们没有将其子类化,因此对super的调用找不到该方法.

您想要的称为方法混乱.但是请注意,您的代码可能会破坏某些内容.由Scot Stevenson撰写的关于 Theocacao的文章有关旧的Objective-C运行时中的方法混淆, 马特·加拉格尔(Matt Gallagher)的《可可与爱》 上有一篇关于新目标中方法混乱的文章-C 2.0运行时并对其进行简单的替换.

或者,您可以对类进行子类化,然后使用子类或使用

@implementation SampleClass (filePathResolver)
-(NSString*) fullPathFromRelativePath:(NSString*) relPath
{
    NSString *result = [super fullPathFromRelativePath: relPath];

  ... do some stuff with the old result

    return result;
}

Note and clarification: From what I can see in the Apple Docs, it appears to me that this should be allowed?

Categories docs at developer.apple.com: When a category overrides an inherited method, the method in the category can, as usual, invoke the inherited implementation via a message to super. However, if a category overrides a method that already existed in the category's class, there is no way to invoke the original implementation.

解决方案

Categories extend the original class, but they don't subclass it, therefore a call to super doesn't find the method.

What you want is called Method Swizzling. But be aware that your code could break something. There's an article on Theocacao written by Scot Stevenson about Method Swizzling in the old Objective-C runtime, Cocoa with Love by Matt Gallagher has an article about Method Swizzling in the new Objective-C 2.0 runtime and a simple replacement for it.

Alternatively, you could subclass the class and then either use the subclass or use + (void)poseAsClass:(Class)aClass to replace the superclass. Apple writes:

A method defined by a posing class can, through a message to super, incorporate the superclass method it overrides.

Be aware that Apple has deprecated poseAsClass: in Mac OS X 10.5.

这篇关于在目标C类别中使用超级吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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