可以通过class_addProperty()
向类添加形式属性:
BOOL class_addProperty(Class cls,
const char *name,
const objc_property_attribute_t *attributes,
unsigned int attributeCount)
前两个参数是不言自明的.第三个参数是属性属性数组,每个属性属性都是一个名称-值对,遵循Objective-Ctype encodings for declared properties.请注意,文档中仍然提到了用于属性编码的逗号分隔字符串.逗号分隔字符串中的每个段由一个objc_property_attribute_t
实例表示.此外,除了id
的泛型@
类型编码之外,objc_property_attribute_t
还接受类名.
下面是一个程序的初稿,它动态地将一个名为name
的属性添加到一个已经有一个名为_privateName
的实例变量的类中:
#include <objc/runtime.h>
#import <Foundation/Foundation.h>
@interface SomeClass : NSObject {
NSString *_privateName;
}
@end
@implementation SomeClass
- (id)init {
self = [super init];
if (self) _privateName = @"Steve";
return self;
}
@end
NSString *nameGetter(id self, SEL _cmd) {
Ivar ivar = class_getInstanceVariable([SomeClass class], "_privateName");
return object_getIvar(self, ivar);
}
void nameSetter(id self, SEL _cmd, NSString *newName) {
Ivar ivar = class_getInstanceVariable([SomeClass class], "_privateName");
id oldName = object_getIvar(self, ivar);
if (oldName != newName) object_setIvar(self, ivar, [newName copy]);
}
int main(void) {
@autoreleasepool {
objc_property_attribute_t type = { "T", "@\"NSString\"" };
objc_property_attribute_t ownership = { "C", "" }; // C = copy
objc_property_attribute_t backingivar = { "V", "_privateName" };
objc_property_attribute_t attrs[] = { type, ownership, backingivar };
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:@"Jobs"];
NSLog(@"%@", [o name]);
}
}
其(修剪)输出:
Steve
Jobs
应该更仔细地编写getter和setter方法,但这应该足以作为如何在运行时动态添加形式属性的示例.