目录

Objective-C - 构成(C - Posing)

在开始在Objective-C中进行构建之前,我想提醒您注意,在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操作中受到影响。

↑回到顶部↑
WIKI教程 @2018