iOS开发-获取属性和方法

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);
}
本文转自Fly_Elephant博客园博客,原文链接:http://www.cnblogs.com/xiaofeixiang/p/5096786.html,如需转载请自行联系原作者

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值