How do I dynamically subclass a class and create a subclass in Objective C?

I want to dynamically subclass a class (say NSString) and instantiate that subclass for testing purposes. How can I do this in Objective C?

+1


a source to share


1 answer


I suspect that you do not need to do what you are trying to do, but without much detail it is impossible to know for sure. Because Objective-C is a late-bound language, subclassing is rarely required for testing purposes. Instead, browse through the category categories or consider a redesign so you can pass the test double (or stub, fake, or mock) with a type parameter id

or protocol-compliant.



For interest, you can use objc_allocateClassPair(Class superclass, const char *name, size_t extraBytes)

to highlight a new class. You can add methods with class_addMethod(Class cls, SEL name, IMP imp, const char *types)

and ivars with class_addIvar(Class cls, const char *name, size_t size, uint8_t alignment, const char *types)

. Finally, you must register a new class using objc_registerClassPair(Class cls)

. See the Objective-C 2.0 Runtime Reference for details . If I find the time, I'll post the code and post it here.

+1


a source







All Articles