runtime是oc的真面目。oc底層的一套c語言API.編碼
unsigned int count; //獲取屬性列表 objc_property_t *propertyList = class_copyPropertyList([self class], &count); for (unsigned int i=0; i<count; i++) { const char *propertyName = property_getName(propertyList[i]); NSLog(@"property---->%@", [NSString stringWithUTF8String:propertyName]); } //獲取方法列表 Method *methodList = class_copyMethodList([self class], &count); for (unsigned int i; i<count; i++) { Method method = methodList[i]; NSLog(@"method---->%@", NSStringFromSelector(method_getName(method))); } //獲取成員變量列表 Ivar *ivarList = class_copyIvarList([self class], &count); for (unsigned int i; i<count; i++) { Ivar myIvar = ivarList[i]; const char *ivarName = ivar_getName(myIvar); NSLog(@"Ivar---->%@", [NSString stringWithUTF8String:ivarName]); } //獲取協議列表 __unsafe_unretained Protocol **protocolList = class_copyProtocolList([self class], &count); for (unsigned int i; i<count; i++) { Protocol *myProtocal = protocolList[i]; const char *protocolName = protocol_getName(myProtocal); NSLog(@"protocol---->%@", [NSString stringWithUTF8String:protocolName]); }
Class clazz = Person.class; unsigned int count = 0; Person *person = [[Person alloc]init]; NSDictionary *dict = @{@"name":@"zhangsan",@"age":@19, @"height": @1.75}; Ivar *ivars = class_copyIvarList(clazz, &count); for (int i = 0; i < count; i++) { const char *cname = ivar_getName(ivars[i]); NSString *name = [NSString stringWithUTF8String:cname]; NSString *key = [name substringFromIndex:1]; const char *coding = ivar_getTypeEncoding(ivars[i]); // 獲取類型 NSString *strCode = [NSString stringWithUTF8String:coding]; id value = dict[key]; if ([strCode isEqualToString:@"f"]) {// 判斷類型是不是float value = @(0.0); } [person setValue:value forKey:key]; } NSLog(@"%@", person);
- (void)encodeWithCoder:(NSCoder *)aCoder { unsigned int count = 0; Ivar *ivars = class_copyIvarList(self.class, &count); for (int i = 0; i < count; i++) { const char *cname = ivar_getName(ivars[i]); NSString *name = [NSString stringWithUTF8String:cname]; NSString *key = [name substringFromIndex:1]; id value = [self valueForKey:key]; // 取出key對應的value [aCoder encodeObject:value forKey:key]; // 編碼 } } - (id)initWithCoder:(NSCoder *)aDecoder { if (self = [super init]) { unsigned int count = 0; Ivar *ivars = class_copyIvarList(self.class, &count); for (int i = 0; i < count; i++) { const char *cname = ivar_getName(ivars[i]); NSString *name = [NSString stringWithUTF8String:cname]; NSString *key = [name substringFromIndex:1]; id value = [aDecoder decodeObjectForKey:key]; // 解碼 [self setValue:value forKey:key]; // 設置key對應的value } } return self; }
其餘應用場景:spa