- 不能向编译后得到的类中增加实例变量。
- 能向运行时创建的类中添加实例变量。
解释下:
- 因为编译后的类已经注册在 runtime 中,类结构体中的 objc_ivar_list 实例变量的链表和 instance_size 实例变量的内存大小已经确定,同时 runtime 会调用 class_setIvarLayout 或 class_setWeakIvarLayout 来处理 strong weak 引用。所以不能向存在的类中添加实例变量。
- 运行时创建的类是可以添加实例变量,调用 class_addIvar 函数。但是得在调用 objc_allocateClassPair 之后,objc_registerClassPair 之前,原因同上。
动态构建类的代码示例:
#pragma mark - Runtime Class Construct
int32_t testRuntimeMethodIMP(id self, SEL _cmd, NSDictionary *dic) {
NSLog(@"testRuntimeMethodIMP: %@", dic);
// Print:
// testRuntimeMethodIMP: {
// a = "para_a";
// b = "para_b";
// }
return 99;
}
- (void)runtimeConstruct {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
Class cls = objc_allocateClassPair(SuperClass.class, "RuntimeSubClass", 0);
// Method returns: "int32_t"; accepts: "id self", "SEL _cmd", "NSDictionary *dic". So use "i@:@" here.
class_addMethod(cls, @selector(testRuntimeMethod), (IMP) testRuntimeMethodIMP, "i@:@");
// You can only register a class once.
objc_registerClassPair(cls);
id sub = [[cls alloc] init];
NSLog(@"%@, %@", object_getClass(sub), class_getSuperclass(object_getClass(sub))); // Print: RuntimeSubClass, SuperClass
Class metaCls = objc_getMetaClass("RuntimeSubClass");
if (class_isMetaClass(metaCls)) {
NSLog(@"YES, %@, %@, %@", metaCls, class_getSuperclass(metaCls), object_getClass(metaCls)); // Print: YES, RuntimeSubClass, SuperClass, NSObject
} else {
NSLog(@"NO");
}
unsigned int outCount = 0;
Method *methods = class_copyMethodList(cls, &outCount);
for (int32_t i = 0; i < outCount; i++) {
Method method = methods[i];
NSLog(@"%@, %s", NSStringFromSelector(method_getName(method)), method_getTypeEncoding(method));
}
// Print: testRuntimeMethod, i@:@
free(methods);
int32_t result = (int) [sub performSelector:@selector(testRuntimeMethod) withObject:@{@"a":@"para_a", @"b":@"para_b"}];
NSLog(@"%d", result); // Print: 99
// Destroy instances of cls class before destroy cls class.
sub = nil;
// Do not call this function if instances of the cls class or any subclass exist.
objc_disposeClassPair(cls);
#pragma clang diagnostic pop
}
#pragma mark - Runtime Ivar&Property Construct
NSString * runtimePropertyGetterIMP(id self, SEL _cmd) {
Ivar ivar = class_getInstanceVariable([self class], "_runtimeProperty");
return object_getIvar(self, ivar);
}
void runtimePropertySetterIMP(id self, SEL _cmd, NSString *s) {
Ivar ivar = class_getInstanceVariable([self class], "_runtimeProperty");
NSString *old = (NSString *) object_getIvar(self, ivar);
if (![old isEqualToString:s]) {
object_setIvar(self, ivar, s);
}
}
- (void)aboutIvarAndProperty {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
// 1: Add property and getter/setter.
Class cls = objc_allocateClassPair(SuperClass.class, "RuntimePropertySubClass", 0);
BOOL b = class_addIvar(cls, "_runtimeProperty", sizeof(cls), log2(sizeof(cls)), @encode(NSString));
NSLog(@"%@", b ? @"YES" : @"NO"); // Print: YES
objc_property_attribute_t type = {"T", "@\"NSString\""};
objc_property_attribute_t ownership = {"C", ""}; // C = copy
objc_property_attribute_t isAtomic = {"N", ""}; // N = nonatomic
objc_property_attribute_t backingivar = {"V", "_runtimeProperty"};
objc_property_attribute_t attrs[] = {type, ownership, isAtomic, backingivar};
class_addProperty(cls, "runtimeProperty", attrs, 4);
class_addMethod(cls, @selector(runtimeProperty), (IMP) runtimePropertyGetterIMP, "@@:");
class_addMethod(cls, @selector(setRuntimeProperty), (IMP) runtimePropertySetterIMP, "v@:@");
// You can only register a class once.
objc_registerClassPair(cls);
// 2: Print all properties.
unsigned int outCount = 0;
objc_property_t *properties = class_copyPropertyList(cls, &outCount);
for (int32_t i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
NSLog(@"%s, %s\n", property_getName(property), property_getAttributes(property));
}
// Print:
// runtimeProperty, T@"NSString",C,N,V_runtimeProperty
free(properties);
// 3: Print all ivars.
Ivar *ivars = class_copyIvarList(cls, &outCount);
for (int32_t i = 0; i < outCount; i++) {
Ivar ivar = ivars[i];
NSLog(@"%s, %s\n", ivar_getName(ivar), ivar_getTypeEncoding(ivar));
}
// Print:
// _runtimeProperty, {NSString=#}
free(ivars);
// 4: Use runtime property.
id sub = [[cls alloc] init];
[sub performSelector:@selector(setRuntimeProperty) withObject:@"It-is-a-runtime-property."];
NSString *s = [sub performSelector:@selector(runtimeProperty)]; //[sub valueForKey:@"runtimeProperty"];
NSLog(@"%@", s); // Print: It-is-a-runtime-property.
// 5: Clear.
// Destroy instances of cls class before destroy cls class.
sub = nil;
// Do not call this function if instances of the cls class or any subclass exist.
objc_disposeClassPair(cls);
#pragma clang diagnostic pop
}
更多:iOS面试题合集