Objective-C 的 Posing 伪装类

在开始介绍 Objective-C 中的 Posing 之前,我想提醒您注意,在 Mac OS X 10.5 中已声明不推荐使用 posing,此后将无法使用。 所以对于那些不关心这些弃用方法的人可以跳过这一章。

Objective-C 允许一个类完全替换程序中的另一个类。 替换类被称为"伪装成"目标类。 对于支持 posing 的版本,发送到目标类的所有消息都由 posing 类接收。

NSObject 包含 poseAsClass − 使我们能够如上所述替换现有类的方法。


Posing 的限制

  • 一个类只能伪装成它的直接或间接超类之一。

  • posing 伪装类不得定义目标类中不存在的任何新实例变量(尽管它可以定义或覆盖方法)。

  • 目标类在伪装之前可能没有收到任何消息。

  • posing 伪装类可以通过 super 调用重写的方法,从而合并目标类的实现。

  • 一个 posing 伪装类可以重写类别中定义的方法。

#import <Foundation/Foundation.h>

@interface MyString : NSString

@end

@implementation MyString

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target
withString:(NSString *)replacement {
   NSLog(@"The Target string is %@",target);
   NSLog(@"The Replacement string is %@",replacement);
}

@end

int main() {
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   [MyString poseAsClass:[NSString class]];
   NSString *string = @"Test";
   [string stringByReplacingOccurrencesOfString:@"a" withString:@"c"];
   
   [pool drain];
   return 0;
}

现在当我们在较旧的 Mac OS X(V_10.5 或更早版本)中编译并运行该程序时,我们将得到以下结果。

2013-09-22 21:23:46.829 Posing[372:303] The Target string is a
2013-09-22 21:23:46.830 Posing[372:303] The Replacement string is c

在上面的例子中,我们只是用我们的实现污染了原来的方法,这将影响到所有使用上述方法的 NSString 操作。