gpt4 book ai didi

objective-c - 在 Objective C 类别中使用 Super?

转载 作者:太空狗 更新时间:2023-10-30 03:11:29 25 4
gpt4 key购买 nike

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

我已经调查过了,看起来 Categories 应该允许我这样做,但我想在我的新方法中使用旧方法的结果,使用 super 来获取旧方法的结果。

不过,每当我尝试这样做时,都会调用我的方法,但“super”为零……知道为什么吗?我正在使用 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 中看到的内容,在我看来应该允许这样做?

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.

最佳答案

类别扩展原始类,但它们不对其进行子类化,因此对 super 的调用找不到方法。

你要的叫Method Swizzling .但请注意,您的代码可能会破坏某些东西。在 Theocacao written by Scot Stevenson 上有一篇文章关于旧 Objective-C 运行时中的 Method Swizzling,Cocoa with Love by Matt Gallagher在新的 Objective-C 2.0 运行时中有一篇关于 Method Swizzling 的文章以及它的简单替代品。

或者,您可以将类子类化,然后使用子类或使用 + (void)poseAsClass:(Class)aClass替换父类(super class)。苹果写道:

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

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

关于objective-c - 在 Objective C 类别中使用 Super?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1405060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com