Just to recap: For existing classes we add attributes using the class_addProperty method. For dynamically created classes we add attributes using class_addIvar, which changes the memory layout of an existing class. A class is created dynamically through objc_allocateClassPair, then Ivar is created by calling class_addIvar, and finally the class is registered through objc_registerClassPair. Pair = Pair = Pair = Pair = Pair = Pair = Pair = Pair This is because metaclasses are also created when classes are created.
-(void)creatClass {NSString *className = @"dynaminClass"; if (! NSClassFromString(className)) { Class newClass = objc_allocateClassPair(NSString.class, className.UTF8String, 0); class_addMethod(newClass, @selector(test), (IMP)funcIMP, "v@:"); objc_registerClassPair(newClass); -(void)creatInstance {Class newClass = NSClassFromString(@"dynaminClass"); id intanceOfClass = [[newClass alloc] init]; // [intanceOfClass eat]; [intanceOfClass selector :@selector(func)]; Void funcIMP(Class self, SEL _cmd) {Class Class = [self Class]; // class: dynaminClass, sel: test.nslog (@"self: % @sel: %s", class, _cmd); }Copy the code
Let’s get back to the problem. What happens if you remove the if condition for creating a class and change the class name to an existing class name? I’m sure you all know that, but here’s a guess:
1, I don’t want to crash. I don’t want to crash. I don’t want to crash. If you create two identical classes for me, which one should I look for? Runtime means I’m confused too, which will cause runtime confusion and unexpected problems.
2, will crash
Try to run, not out of expectation, really collapse, reason: EXC_BAD_ACCESS, this problem believe a lot of people have a headache, do not mention, I want to quietly ðŸ˜. > > class > metaclass > root metaclass, where only instance can create multiple (address is different), now I dynamically registered a class, the class name is the name of the existing class, can create successfully and open up memory? No, objc_allocateClassPair doesn’t crash because its internal return returns directly, and it doesn’t crash because there is no memory operation. The objc_registerClassPair registration operation will operate on memory and crash in the data function (need to run source code) :
class_rw_t* data() const {
return (class_rw_t *)(bits & FAST_DATA_MASK);
}
Copy the code
Since the class is not in memory at all, memory operations must report EXC_BAD_ACCESS.
Summary: the source code will not take you to see, there is no special internal operation, the reason for this is that I met the interview before. I haven’t seen this question in my online interview questions, so I thought I’d make a brief explanation for my friends. There are two main topics:
1. Will only one class be created when creating a class dynamically? No, there are corresponding metaclasses (see source code)
2. What happens when you dynamically add a class with the same name as an existing class? Crash, EXC_BAD_ACCESS.