发布于 2015-07-05 11:53:25 | 199 次阅读 | 评论: 0 | 来源: 网络整理

开始之前冒充在Objective-C,必须要说明的是,冒充宣布弃用在Mac OS X10.5,它此后都不再使用了。因此,对于那些不关心这些过时的方法的同学可以跳过本章。

Objective-C的全取代另一个阶级在一个程序中允许类。更换类说“构成”目标类。

对于支持冒充的版本,所有的消息发送到目标类的,而不是收到通过冒充的类。

NSObject 包含 poseAsClass 方法,使我们能够取代现有的的类,就像上面说。

Restrictions/冒充限制

  • 一个类可能只对作为其直接或间接的父类之一。

  • 冒充类绝不能定义任何新的实例变量目标类(虽然它可能定义或重写方法)不存在。

  • 目标类可能没有收到任何消息之前冒充。

  • 冒充类可以通过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 操作。

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务