本文介绍了在目标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中看到的内容,我看来应该允许这样做?

解决方案

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

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

或者,您可以对类进行子类化,然后使用子类或使用 + (void)poseAsClass:(Class)aClass 来替换超类.苹果写道:

请注意,Apple已在Mac OS X 10.5中弃用poseAsClass:.

I'd like to override a method in an Objective C class that I don't have the source to.

I've looked into it, and it appears that Categories should allow me to do this, but I'd like to use the result of the old method in my new method, using super to get the old methods result.

Whenever I try this though, my method gets called, but "super" is nil... Any idea why? I'm doing iPhone development with the XCode 2.2 SDK. I'm definitely working with an instance of a class, and the method of the class is an instance method.

@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 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:

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

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

09-22 08:38