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]);
}
}
网友评论