- Objective-C 基础
- Objective-C - 首页
- Objective-C - 概述
- Objective-C - 环境搭建
- Objective-C - 程序结构
- Objective-C - 基本语法
- Objective-C - 数据类型
- Objective-C - 变量
- Objective-C - 常量
- Objective-C - 运算符
- Objective-C - 循环
- Objective-C - 决策
- Objective-C - 函数
- Objective-C - 块 (Blocks)
- Objective-C - 数字
- Objective-C - 数组
- Objective-C - 指针
- Objective-C - 字符串
- Objective-C - 结构体
- Objective-C - 预处理器
- Objective-C - Typedef
- Objective-C - 类型转换
- Objective-C - 日志处理
- Objective-C - 错误处理
- 命令行参数
- 高级 Objective-C
- Objective-C - 类和对象
- Objective-C - 继承
- Objective-C - 多态
- Objective-C - 数据封装
- Objective-C - 分类 (Categories)
- Objective-C - 模拟 (Posing)
- Objective-C - 扩展 (Extensions)
- Objective-C - 协议 (Protocols)
- Objective-C - 动态绑定
- Objective-C - 组合对象
- Obj-C - Foundation 框架
- Objective-C - 快速枚举
- Obj-C - 内存管理
- Objective-C 有用资源
- Objective-C - 快速指南
- Objective-C - 有用资源
- Objective-C - 讨论
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 操作。
广告