Che*_*Dev 0 objective-c nsarray kvc
我有几个NSArray,它们包含相互关联的UIView对象集合(NSArrays是soundView0,soundView1,soundView2和soundView3).我希望能够将BOOL属性与将在数组中启用/解释UIViews的整个数组相关联.
什么是最干净/最恰当的方法来完成这个?
子类化NSArray
可能很困难,当您只需要一个额外的属性时,您可以通过类别和运行时函数使用另一个选项.写一个类别NSArray
,添加属性并使用相关对象为属性提供存储.此代码应该足够,只需根据您的应用程序的命名约定重命名.
@interface NSArray (MyExtensions)
@property (nonatomic) BOOL myProperty
@end
@implementation NSArray (MyExtensions)
static char MyPropertyKey;
- (void)setMyProperty:(BOOL)myProperty
{
objc_setAssociatedObject(self, &MyPropertyKey, @(myProperty), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)myProperty
{
NSNumber *propertyNumber = objc_getAssociatedObject(self, &MyPropertyKey);
return [propertyNumber boolValue];
}
@end
Run Code Online (Sandbox Code Playgroud)