iOS开发数据存储有两种方式,属性列表和对象编码,属性列表可以通过NSArray,NSMutableArray,NSMutableDictionary,存储对象我们可以通过归档和解档来完成。如果我们想通过属性列表存储对象呢?这个时候我们就需要获取对象的属性列表和值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
NSMutableDictionary *mutableDic=[[NSMutableDictionary alloc]init]; u_int count; objc_property_t *properties= class_copyPropertyList([self.msg class ], &count);
for (NSInteger i = 0; i < count ; i++)
{ const char *propertyName = property_getName(properties[i]);
NSString *key = [NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding];
NSString *value=[self.msg valueForKey:key];
[mutableDic setObject:value forKey:key];
} NSString *dataPath = [[NSBundle mainBundle] pathForResource: @"MyData" ofType: @"plist" ];
[mutableDic writeToFile:dataPath atomically:YES]; NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:dataPath]; NSLog( @"%@" ,data);
|
中间的代码objc_property_t获取属性数组,之后通过属性的名称存储对应的值,效果如下:
我们可以获取属性也可以获取方法,跟获取属性类似,代码如下:
1
2
3
4
5
6
7
8
|
u_int methodCount; Method* methods= class_copyMethodList([msg class ], &methodCount);
for ( int i = 0; i < methodCount ; i++)
{ SEL name = method_getName(methods[i]);
NSString *methodName= [NSString stringWithCString:sel_getName(name) encoding:NSUTF8StringEncoding];
NSLog( @"method:%@" ,methodName);
} |
关于方法获取也有一些其他比较实用的方法:
1
2
3
4
5
|
SEL method_getName(Method m) 由Method得到SEL MP method_getImplementation(Method m) 由Method得到IMP函数指针 const char *method_getTypeEncoding(Method m) 由Method得到类型编码信息unsigned int method_getNumberOfArguments(Method m)获取参数个数
char *method_copyReturnType(Method m) 得到返回值类型名称
IMP method_setImplementation(Method m, IMP imp) 为该方法设置一个新的实现 |
除了获取属性和方法我们也可以通过class_copyIvarList获取变量,获取变量值:
1
2
3
4
5
6
7
8
9
|
u_int varCount; Ivar *vars= class_copyIvarList([msg class ], &varCount);
for ( int i = 0; i < varCount ; i++)
{ const char *varname = ivar_getName(vars[i]);
NSString *varName= [NSString stringWithCString:varname encoding:NSUTF8StringEncoding];
NSString *value=[msg valueForKey:varName];
NSLog( @"变量:%@--值:%@" ,varName,value);
} |