动态更改对象的超类 [英] Dynamically change an object's superclass

查看:66
本文介绍了动态更改对象的超类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在运行时更改对象的超类?如果可以,怎么办?

Is it possible to change an object's superclass at runtime? If so, how?

推荐答案

一个简短的问题,一个简短的答案:是的,伊莎(Isa)令人毛骨悚然

a short question, a short answer: yes, isa swizzling

是什么使Objective C动态化?,第66页

一个例子:

我有一个处理与REST-API的连接的类,称为APIClient.在测试中,我想连接到其他服务器.

I have a class that handles connections to a REST-API, it is called APIClient. In testing I want to connect to a different server.

在测试目标中,我子类化APIClient

In the testing target I subclass APIClient

#import "ApiClient.h"

@interface TestApiClient : ApiClient
//…
@end


@interface TestApiClient ()
@property (nonatomic, strong, readwrite) NSURL *baseURL;

@end


@implementation TestApiClient

- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
                                      path:(NSString *)path
                                parameters:(NSDictionary *)parameters
{
    self.baseURL = [NSURL URLWithString:@"http://localhost:8000/"];
    return [super requestWithMethod:method path:path parameters:parameters];
}

@end

在单元测试课程中,我会感到困惑 #import

In the Unit test class I do the swizzling #import

@implementation APIUnitTests


+(void)load
{
    client = [[ApiClient alloc ] init];
    object_setClass(client, [TestApiClient class]);
}

//…
@end

此cas被保存,因为我首先创建了基类的子类,然后将基类替换为该子类.由于子类也是基类,因此这是有效的继承.

This cas is save, as I first created a subclass of an base class and then replaced the latter with the subclass. As the subclass is also a base class, this is valid inheritance.

这篇关于动态更改对象的超类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆