Objective-C 中的模拟 (Posing)



在开始讲解 Objective-C 中的**模拟 (Posing)** 之前,我想提醒您,模拟在 Mac OS X 10.5 中已被弃用,此后不再可用。因此,对于那些不关心这些已弃用方法的人,可以跳过本章。

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

NSObject 包含 `poseAsClass` 方法,使我们能够像上面说的那样替换现有的类。

模拟的限制

  • 一个类只能模拟其直接或间接超类之一。

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

  • 目标类在模拟之前可能没有接收任何消息。

  • 模拟类可以通过 `super` 调用被覆盖的方法,从而结合目标类的实现。

  • 模拟类可以覆盖在分类中定义的方法。

#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 操作。

广告
© . All rights reserved.