gpt4 book ai didi

objective-c - 覆盖子类的所有 setter 和 getter

转载 作者:太空狗 更新时间:2023-10-30 03:49:58 25 4
gpt4 key购买 nike

我想覆盖 setter 和 getter 并找到 objc_property_t 的类,而不是为每个属性单独执行它。

我得到了这样的所有属性:

unsigned int numberOfProperties;
objc_property_t *propertyArray = class_copyPropertyList([self class], &numberOfProperties);
for (NSUInteger i = 0; i < numberOfProperties; i++) {
objc_property_t property = propertyArray[i];
NSString *name = [[NSString alloc] initWithUTF8String:property_getName(property)];

property.getter = SEL; //?
}

这是我想如何覆盖 getter 和 setter 的示例 - 如果有更好的方法,请告诉我。也许是 NSInvocation?

- (UIImage *)backgroundImage
{
return [self overrideGetterWithSelector:NSStringFromSelector(_cmd)];
}

- (void)setBackgroundImage:(UIImage *)backgroundImage
{
[self overrideSetterForObject:backgroundImage forSelector:NSStringFromSelector(_cmd)];
}

或者有没有办法拦截发送给类的所有消息?

我的目标是制定一种通用方法来在两次启动之间存储类的属性。你可能想问为什么我不使用 NSUserDefaultsNSKeyedArchiver。好吧,我正在使用 NSKeyedArchiver - 我不想手动覆盖每一个 setter 和 getter。

最佳答案

您可以只使用来自 objc 运行时的 class_replaceMethod 来替换 getter 的实现。

例子:

- (void)replaceGetters {
unsigned int numberOfProperties;
objc_property_t *propertyArray = class_copyPropertyList([self class], &numberOfProperties);
for (NSUInteger i = 0; i < numberOfProperties; i++) {
objc_property_t property = propertyArray[i];
const char *attrs = property_getAttributes(property);
NSString *name = [[NSString alloc] initWithUTF8String:property_getName(property)];

// property.getter = SEL; //?
// becomes
class_replaceMethod([self class], NSSelectorFromString(name), (IMP)myNewGetter, attrs);
}
}

id myNewGetter(id self, SEL _cmd) {
// do whatever you want with the variables....

// you can work out the name of the variable using - NSStringFromSelector(_cmd)
// or by looking at the attributes of the property with property_getAttributes(property);
// There's a V_varName in the property attributes
// and get it's value using - class_getInstanceVariable ()
// Ivar ivar = class_getInstanceVariable([SomeClass class], "_myVarName");
// return object_getIvar(self, ivar);
}

关于objective-c - 覆盖子类的所有 setter 和 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20664586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com