Is it possible to change an object's superclass at runtime? If so, how?
Asked
Active
Viewed 5,465 times
9
-
Have a look at http://stackoverflow.com/questions/11221110/my-isa-swizzling-breaks-kvo for an example of an isa swizzle. – mttrb Feb 25 '13 at 05:29
-
1Also, what do mean by "the superclass of an object"? An *object* has no superclass. An object has a class and its class has a superclass. If you, however, alter the superclass of the class of the object, **all members of that class will be affected,** not only that single object. – Feb 25 '13 at 05:31
-
2why superclass not current class? what happen to the current class? you have to think carefully first – Bryan Chen Feb 25 '13 at 05:33
1 Answers
12
a short question, a short answer: yes, isa swizzling
What Makes Objective C Dynamic?, page 66
An example:
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.
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
In the Unit test class I do the swizzling #import
@implementation APIUnitTests
+(void)load
{
client = [[ApiClient alloc ] init];
object_setClass(client, [TestApiClient class]);
}
//…
@end
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.

vikingosegundo
- 52,040
- 14
- 137
- 178
-
2This sounds extremely dangerous. Why on earth would you want to? – Richard Brown Feb 25 '13 at 05:35
-
2if done right it is very powerful, apple uses it for KVO: http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/KeyValueObserving/Articles/KVOImplementation.html – vikingosegundo Feb 25 '13 at 05:36
-
I personally use it to inspect code: I subclass and overwrite the methods I am interested in to log some informations and call the original methods on super. – vikingosegundo Feb 25 '13 at 05:40
-
-