📜  Objective-C的姿势

📅  最后修改于: 2020-11-03 16:01:56             🧑  作者: Mango


在Objective-C开始约造像之前,我想提请你注意,冒充是在Mac OS X 10.5宣布弃用,这之后是不能使用的。因此,对于那些不关心这些不建议使用的方法的人可以跳过本章。

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

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

摆姿势的限制

  • 一个类只能构成其直接或间接超类之一。

  • 构成类不能定义目标类不存在的任何新实例变量(尽管它可以定义或重写方法)。

  • 在摆姿势之前,目标班级可能尚未收到任何消息。

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

  • 冒充类可以覆盖类别中定义的方法。

#import 

@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操作中受到影响。