Objective-C Posing
在开始在 Objective-C 中讲解 Posing 之前,我想提醒您,在 Mac OS X 10.5 中, Posing 已被宣布为弃用,此后将无法使用。因此,对于那些不关心这些不推荐的方法的人,可以跳过本章。
Objective-C 支持一个类完全替换程序中的另一个类。替换类被称为目标类的 Posing。对于支持 Posing 的版本,发送到目标类的所有消息都由 Posing 类接收。
NSObject 包含 poseAsClass − 方法,使我们能够替换如上所述的现有类。
Posing 的限制
- 类只能作为其直接或间接超类之一。
- posing 类不能定义目标类中不存在的任何新实例变量(尽管它可以定义或重写方法)。
- 目标类在 posing 之前可能没有收到任何消息。
- posing 类可以通过
super调用重写的方法,从而合并目标类的实现。 - posing 类可以覆盖类别中定义的方法。
#import <Foundation/Foundation.h>@interface MyString : NSString@end@implementation MyString- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)targetwithString:(NSString *)replacement {NSLog(@"The Target string is %@",target);NSLog(@"The Replacement string is %@",replacement);}@endint main() {NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];[MyString poseAsClass:[NSString class]];NSString *string = @"Test";[string stringByReplacingOccurrencesOfString:@"a" withString:@"c"];[pool drain];return 0;}
结果如下:
2022-07-07 21:23:46.829 Posing[372:303] The Target string is a2022-07-07 21:23:46.830 Posing[372:303] The Replacement string is c
在上面的实例中,我们只是用我们的实现修改了原始方法,这将在使用上述方法的所有 NSString 操作中受到影响。