您的位置:首页 > 其它

RunTime 获取对象属性和方法

2015-11-03 16:56 453 查看
RunTime中的效果感觉和Java中的反射差不多,在动态也就是在代码运行的时候来获取这个对象的属性和方法。 在对数据库的写法上面可以用到,如:需要写SQL语句和对象的对应的时候, 可以用这种形式来进行封装,这样的话, 通过一个类能处理好项目中的SQL的创建或者查询等操作。 一些高层的封装上面也需要用到。 简单的获取属性和方法的如下代码:

#import <Foundation/Foundation.h>

@interface Student : NSObject

@property(nonatomic,assign)NSString *userName;
@property(nonatomic,assign)NSString *sex;
@property(nonatomic)NSInteger age;

- (void)happy:(NSString *)happyName;

- (void)readBook;

@end
#import "Student.h"

@implementation Student

- (void)happy:(NSString *)happyName{

NSLog(@"爱好打-->%@",happyName);
}

- (void)readBook{
NSLog(@"文学小说");
}


获取类如下:
#import <Foundation/Foundation.h>

@interface EntityTools : NSObject

- (void)gainParmers:(NSString *)className;

@end
#import "EntityTools.h"
#import <objc/runtime.h>

@implementation EntityTools

#pragma mark 获取 属性, 方法, 相当于java中的反射
- (void)gainParmers:(NSString *)className{
Class  classEntity = NSClassFromString(className);
NSObject *stu =  [[classEntity alloc] init];

unsigned int count;
// 获取属性列表
objc_property_t *propertyList = class_copyPropertyList([stu 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([stu class], &count);
for (unsigned int i = 0; i<count; i++) {
Method method = methodList[i];
SEL  sel = method_getName(method);
NSString *methodName = NSStringFromSelector(sel);
if ([methodName isEqualToString:@"readBook"]) {
NSLog(@"method---->%@", methodName);
[stu performSelector:sel];
}else if([methodName isEqualToString:@"happy:"]){
NSLog(@"method---->%@", methodName);
[stu performSelector:sel withObject:@"篮球"];
}
}
}


调用:
#import <Foundation/Foundation.h>
#import "EntityTools.h"
#import "Student.h"

int main(int argc, const char * argv[]) {
@autoreleasepool {

[[[EntityTools alloc]init] gainParmers:@"Student"];

}
return 0;
}

运行结果如下:
2015-11-03 16:55:17.277 RunTime学习[3555:1330871] property----=>userName
2015-11-03 16:55:17.278 RunTime学习[3555:1330871] property----=>sex
2015-11-03 16:55:17.278 RunTime学习[3555:1330871] property----=>age
2015-11-03 16:55:17.278 RunTime学习[3555:1330871] method---->happy:
2015-11-03 16:55:17.278 RunTime学习[3555:1330871] 爱好打-->篮球
2015-11-03 16:55:17.278 RunTime学习[3555:1330871] method---->readBook
2015-11-03 16:55:17.279 RunTime学习[3555:1330871] 文学小说
Program ended with exit code: 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息