美文网首页iOS学习
class_addProperty运行时方法

class_addProperty运行时方法

作者: yu_briebook | 来源:发表于2017-02-27 16:57 被阅读0次

    static char *propertykey = nil;

    NSString *getterMeth(id self, SEL _cmd) {

    Ivar ivar = class_getInstanceVariable([SomeClass class],propertykey );

    return object_getIvar(self, ivar);

    }

    void setterMeth(id self, SEL _cmd, NSString *name) {

    Ivar ivar = class_getInstanceVariable([SomeClass class], propertykey);

    id oldName = object_getIvar(self, ivar);

    if (oldName != ame) object_setIvar(self, ivar, [name copy]);

    }

    int main(void) {

    propertykey = "_privaName";

    @autoreleasepool {

    objc_property_attribute_t types = { "T", "@\"NSString\"" };

    objc_property_attribute_t ownership = { "C", "" }; // C = copy

    objc_property_attribute_t backIvar  = { "V", "_privateName" };

    objc_property_attribute_t attrs[] = { types, ownership, backIvar };

    class_addProperty([SomeClass class], "name", attrs, 3);

    class_addMethod([SomeClass class], @selector(name), (IMP)nameGetter, "@@:");

    class_addMethod([SomeClass class], @selector(setName:), (IMP)nameSetter, "v@:@");

    id o = [SomeClass new];

    NSLog(@"%@", [o name]);

    [o setName:@"your Name"];

    NSLog(@"%@", [o name]);

    }

    }

    相关文章

      网友评论

        本文标题:class_addProperty运行时方法

        本文链接:https://www.haomeiwen.com/subject/jpgzwttx.html