FMDB将对象放进数据库[二](使用runtime)

上次写了一篇利用FMDB将对象放进数据库 

http://www.cnblogs.com/hanjian/p/4344112.html

像我写的HJShop是及其简单的,如果对象有很多属性,那岂不是很麻烦

这里我们就要用到运行时机制了

首先用Ivar *class_copyIvarList(Class cls, unsigned int *outCount)

得到对象所有的属性,然后遍历所有属性进行ecode和dcode

听起来可能有些复杂其实只要稍稍改写一下两个方法就可以了

下面开始正文:导入头文件是必不可少的

 #import <objc/runtime.h>

下面是运用运行时写的方法,当然KVC在这里不可少(KVC本身就是运行时的一部分)

- (void)encodeWithCoder:(NSCoder *)aCoder

{

    unsigned int count = 0;

    Ivar *ivars = class_copyIvarList([self class], &count);

    for (int i = 0; i < count; i++) {

        Ivar ivar = ivars[i];

        const char *name = ivar_getName(ivar);

        NSString *key = [NSString stringWithUTF8String:name];

        [aCoder encodeObject:[self valueForKeyPath:key] forKey:key];

    }

       free(ivars); 

}


- (id)initWithCoder:(NSCoder *)aDecoder

{

    if (self = [super init]) {

        unsigned int count = 0;

        Ivar *ivars = class_copyIvarList([self class], &count);

        for (int i = 0; i < count; i++) {

            Ivar ivar = ivars[i];

            const char *name = ivar_getName(ivar);

            NSString *key = [NSString stringWithUTF8String:name];

            [self setValue:[aDecoder decodeObjectForKey:key] forKey:key];

        }

              free(ivars); 

    }

    return self;

} 

 

总结:运行时很强大,变量、类、方法都可以改写。有时间再详细讲讲。

Ivar *class_copyIvarList(Class cls, unsigned int *outCount)  

获取某个类内部的所有成员变量

 

Method *class_copyMethodList(Class cls, unsigned int *outCount)  

获取某个类内部所有方法

 

Method class_getInstanceMethod(Class cls, SEL name)

获取某个实例方法(对象方法,减号-开头)

 

Method class_getClassMethod(Class cls, SEL name)  

获取某个类方法(加号+开头)

 

void method_exchangeImplementations(Method m1, Method m2)   

交换两个方法

 

posted @ 2015-03-23 13:26  罕见  阅读(297)  评论(0编辑  收藏  举报