Objective c 使用objc/runtime.h设置变量的Setter和Getter
我有很好的对象Setter和Getter代码。如何像这里一样使用objc/runtime.h对BOOL执行同样的操作? objc_getAssociatedObject需要对象Objective c 使用objc/runtime.h设置变量的Setter和Getter,objective-c,setter,getter,Objective C,Setter,Getter,我有很好的对象Setter和Getter代码。如何像这里一样使用objc/runtime.h对BOOL执行同样的操作? objc_getAssociatedObject需要对象 .h #import <Foundation/Foundation.h> @interface UITableView (Additions) @property (nonatomic, retain) NSNumber *allowReplenishment; @end .m #import "UITab
.h
#import <Foundation/Foundation.h>
@interface UITableView (Additions)
@property (nonatomic, retain) NSNumber *allowReplenishment;
@end
.m
#import "UITableView+Additions.h"
#import <objc/runtime.h>
@implementation UITableView (Additions)
- (NSNumber *)allowReplenishment {
return objc_getAssociatedObject(self, @selector(allowReplenishment));
}
- (void)setAllowReplenishment:(NSNumber *)value {
objc_setAssociatedObject(self, @selector(allowReplenishment), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
.h
#进口
@界面UITableView(添加)
@属性(非原子,保留)NSNumber*AllowerPlenishment;
@结束
M
#导入“UITableView+Additions.h”
#进口
@实现UITableView(添加)
-(NSNumber*)允许授权{
返回objc_getAssociatedObject(self,@selector(allowReplenishment));
}
-(void)setAllowReplenishment:(NSNumber*)值{
objc_setAssociatedObject(self、@selector(allowerPlenishment)、value、objc_ASSOCIATION_RETAIN_NONATOMIC);
}
@结束
如果要声明您的bool
属性
@属性(非原子,赋值)BOOL为AllowerPlenishment,只需根据需要在setter中创建对象即可:
- (void)setIsAllowReplenishment:(BOOL)isAllowReplenishment
{
NSNumber *isBool = [NSNumber numberWithBool:isAllowReplenishment];
objc_setAssociatedObject(self, @selector(isAllowReplenishment), isBool, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)isAllowReplenishment
{
NSNumber *isBool = objc_getAssociatedObject(self, @selector(isAllowReplenishment));
return isBool.boolValue;
}
使用SEL作为上下文是危险的,因为这个地址可以被其他代码访问(苹果可以使用它,或者你的超类等等)。通常,更好的方法是声明自己的上下文全局
静态void*kIsAllowReplenishmentAssociatedObjectContext=&kIsAllowReplenishmentAssociatedObjectContext编码>并将其作为上下文传递给getter/setter。这个变量只包含它自己的地址,所以你可以像传递任何旧常量一样传递它,但它是一个唯一的值,因为你的应用程序中没有其他东西可以占用相同的内存。