Dynamic Class creation for ios, dynamic class for ios
[Objective-C Runtime dynamic loading] --- dynamically creates Class
Dynamically create Class classes, dynamically add Class member variables and member functions, assign values and values to dynamic variables, and call dynamic functions.
A. Use objc_allocateClassPair to create a Class
Const char * className = "Calculator ";
Class kclass = objc_getClass (className );
If (! Kclass)
{
Class superClass = [NSObject class];
Kclass = objc_allocateClassPair (superClass, className, 0 );
}
B. Use class_addIvar to add a member variable.
NSUInteger size;
NSUInteger alignment;
NSGetSizeAndAlignment ("*", & size, & alignment );
Class_addIvar (kclass, "expression", size, alignment ,"*");
Note:
1. type definition reference: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
2. "*" asterisks represent characters (). The iOS character is 4 bits and uses 4 bits to align with kclass.
C. Use class_addMethod to add a member
Class_addMethod (kclass, @ selector (setExpressionFormula :), (IMP) setExpressionFormula, "v @:@");
Class_addMethod (kclass, @ selector (getExpressionFormula), (IMP) getExpressionFormula ,"@@:");
Static void setExpressionFormula (id self, SEL cmd, id value)
{
NSLog (@ "call setExpressionFormula ");
}
Static void getExpressionFormula (id self, SEL cmd)
{
NSLog (@ "call getExpressionFormula ");
}
Note:
1. type definition reference: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
2. "v @: @", explains the void type of the v-return value, the @-self pointer id type, the-SEL pointer SEL type, and the first parameter of the @-function is the id type.
3. "@:", explanation @-return value id type, @-self pointer id type,-SEL pointer SEL type,
D. Register to the runtime environment
Objc_registerClassPair (kclass );
E. instantiation class
Id instance = [[kclass alloc] init];
F. assign values to variables
Object_setInstanceVariable (instance, "expression", "1 + 1 ");
G. Get the variable value
Void * value = NULL;
Object_getInstanceVariable (instance, "expression", & value );
H. Call a function
[Instance into mselector: @ selector (getExpressionFormula)];