项目结束了,总结一下我用到RUNTime的地方,和大家讨论一下。主要在一下几个方面用到了RUNTime。
1.保存用户本地信息,由于项目中需要一个用户信息是本地的,在下一次登录重新登录之前不会改变,所以就想使用RUNTime和归档联合使用,保存整个类的信息。具体实现如下所示。但是要注意一个问题,就是这个类里不能包括非对象类型的数据,归档只能归档对象类型数据,代码如下供参考
首先,把整个用户信息类写入本地,
+ (void)writeObject:(UserDataObject *)pObject{
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:pObject];
NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
[user setObject:data forKey: [[pObject class] description] ];}
存的是nsdate类型,就需要把类归档,通过RUNTime访问类的所有变量,并归档
unsigned int propertyCount = 0;
objc_property_t *propertyList = class_copyPropertyList([self class], &propertyCount);
for ( int i = 0; i < propertyCount; i++ ) {
objc_property_t *thisProperty = propertyList + i;
const char* propertyName = property_getName(*thisProperty);
NSString *strPropertyName = [NSString stringWithUTF8String:propertyName];
NSString *strFirst = [[strPropertyName substringToIndex:1] capitalizedString ];
strPropertyName = [strPropertyName substringFromIndex:1];
NSString *objName = [NSString stringWithFormat:@"%@%@", strFirst, strPropertyName];
NSString *setMethodName = [NSString stringWithFormat:@"set%@:", objName ];
NSString *getMethodName = [NSString stringWithUTF8String:propertyName];
[self performSelector:NSSelectorFromString(setMethodName) withObject: [pObject performSelector:NSSelectorFromString(getMethodName)]];
}
2.改变时间选择器的颜色,系统的时间选择器默认黑白搭配,而且其属性中并没有改变颜色的属性,这是我们通过RUNTime访问类的所有变量,找到控制颜色的变量,并且在运行时改变其颜色。其实textColor是控制颜色的私有变量
unsigned outCount; int i; objc_property_t *pProperty = class_copyPropertyList([UIDatePicker class], &outCount); for (i = outCount -1; i >= 0; i--) { // 循环获取属性的名字 property_getName函数返回一个属性的名称
NSString *getPropertyName = [NSString stringWithCString:property_getName(pProperty[i]) encoding:NSUTF8StringEncoding]; NSString *getPropertyNameString = [NSString stringWithCString:property_getAttributes(pProperty[i]) encoding:NSUTF8StringEncoding]; if([getPropertyName isEqualToString:@"textColor"]) { [_datePicker setValue:[UIColor blueColor] forKey:@"textColor"]; } NSLog(@"%@====%@",getPropertyNameString,getPropertyName); } self.backgroundColor = [UIColor whiteColor];
}
对RUNTime的了解还不够深入,只是简单的运用了一下,以后会更深层次的去了解