使用objc / runtime.h的变量的Setter和Getter

时间:2017-07-09 09:51:17

标签: objective-c setter getter

我对Object有很好的Setter和Getter代码。如何使用objc / runtime.h这样的BOOL一样吗? objc_getAssociatedObject需要对象

.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

1 个答案:

答案 0 :(得分:0)

如果您要申报bool财产 @property(nonatomic,assign)BOOL isAllowReplenishment,只需根据需要在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;
    }