2017-07-09 2 views
0

私はオブジェクト用のセッターとゲッターのコードを持っています。 objc/runtime.hを使ってBOOLを同じようにするには?あなたはBOOL isAllowReplenishmentは、だけではなく、セッターでオブジェクトを作成(、非アトミック割り当てる) @propertyあなたboolプロパティ宣言したい場合は、必要に応じて objc_getAssociatedObjectは、オブジェクトobjc/runtime.hを使用した変数のセッターとゲッター

.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 

答えて

0

が必要になります。

- (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; 
    } 
+0

使い方このアドレスは他のコード(Appleはスーパークラスなどを使用している可能性があります)からアクセスできるため、コンテキストとしてのSELは危険です。一般的に、より良いアイデアは、あなた自身のコンテキスト 'static void * kIsAllowReplenishmentAssociatedObjectContext =&kIsAllowReplenishmentAssociatedObjectContext;を宣言し、それをゲッター/セッターのコンテキストとして渡すことです。この変数はそれ自身のアドレスを含んでいるだけなので、古い定数のように渡すことができますが、アプリ内の他のメモリが同じメモリを占有することはないため、一意の値です。 – uliwitness

関連する問題