猿问

如何在运行时向对象添加属性?

是否可以在运行时将属性添加到Objective C对象?


如何在运行时向对象添加属性?

鸿蒙传说
浏览 495回答 3
3回答

jeck猫

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

猛跑小猪

如果您查看此处NSKeyValueCoding记录的协议,则可以看到一条消息:- (id)valueForUndefinedKey:(NSString *)key您应该重写该方法以为指定的undefined属性提供自定义结果。当然,这假定您的类使用相应的协议。这种方法通常用于向类提供未知的行为(例如,不存在的选择器)。

暮色呼如

否(即,使用点语法等)。但是您可以使用关联对象来添加存储:如何在对象内部使用objc_setAssociatedObject / objc_getAssociatedObject?。
随时随地看视频慕课网APP
我要回答