在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Object c也有和java相同的方法获取对象的属性列表方法,也就时反射了。 http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html
下面这段代码演示了如何获取类的属性相关信息
- (void)encodeWithCoder:(NSCoder*)coder { Class clazz = [self class]; u_int count; objc_property_t* properties = class_copyPropertyList(clazz, &count); NSMutableArray* propertyArray = [NSMutableArray arrayWithCapacity:count]; for (int i = 0; i < count ; i++) { const char* propertyName = property_getName(properties[i]); [propertyArray addObject:[NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding]]; } free(properties); for (NSString *name in propertyArray) { id value = [self valueForKey:name]; [coder encodeObject:value forKey:name]; } } - (id)initWithCoder:(NSCoder*)decoder { if (self = [super init]) { if (decoder == nil) { return self; } Class clazz = [self class]; u_int count; objc_property_t* properties = class_copyPropertyList(clazz, &count); NSMutableArray* propertyArray = [NSMutableArray arrayWithCapacity:count]; for (int i = 0; i < count ; i++) { const char* propertyName = property_getName(properties[i]); [propertyArray addObject:[NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding]]; } free(properties); for (NSString *name in propertyArray) { id value = [decoder decodeObjectForKey:name]; [self setValue:value forKey:name]; } } return self; } |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论