I want to dynamically subclass a class (say NSString) and instantiate that subclass for testing purposes. How can I do that in Objective C?
I want to dynamically subclass a class (say NSString) and instantiate that subclass for
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I suspect that you don’t need to do what you’re seeking to do, but without more specifics it’s impossible to know for sure. Because Objective-C is a late-bound language, subclassing for testing purposes is rarely required. Instead, take a look at class categories or consider a redesign so that you can pass a test double (either stub, fake or mock) via a parameter of type
idor conforming to a protocol.For interest, you can use
objc_allocateClassPair(Class superclass, const char *name, size_t extraBytes)to allocate a new class. You can add methods usingclass_addMethod(Class cls, SEL name, IMP imp, const char *types)and ivars withclass_addIvar(Class cls, const char *name, size_t size, uint8_t alignment, const char *types). Finally, you should register the new class usingobjc_registerClassPair(Class cls). Find out more in the Objective-C 2.0 Runtime Reference. If I find time, I’ll test some code and post it here.