我真的很喜欢块的工作方式,并认为将它们添加到一些地方会很好,比如为UIRefreshControl
.
所以我创建了category
一个UIRefreshControl
@interface UIRefreshControl (Blocks)
@property (nonatomic, copy) void (^actionBlock)();
- (id)initWitActionBlock:(void (^)())actionBlock;
@end
@implementation UIRefreshControl (Blocks)
- (id)initWitActionBlock: (void (^)())actionBlock {
self = [super init];
if (self) {
self.actionBlock = [actionBlock copy];
[self addTarget:self action:@selector(fireActionBlock) forControlEvents:UIControlEventValueChanged];
}
return self;
}
- (void)fireActionBlock {
self.actionBlock();
}
@end
这是崩溃:原因:'-[UIRefreshControl setActionBlock:]:无法识别的选择器发送到实例
但我真的不太了解积木,而且我也没有真正看到这category
与subclass
做同样的事情之间的区别。
我想我不完全了解属性发生了什么,所以我的问题是我应该怎么做?如果可能的话,这样可以吗?或者也许我不应该这样做?
编辑: *带有相关参考的解决方案感谢@Martin R!
static char const * const ActionBlockKey = "ActionBlockKey";
@interface UIRefreshControl (Blocks)
@property (nonatomic, copy) void (^actionBlock)();
- (id)initWitActionBlock:(void (^)())actionBlock;
@end
@implementation UIRefreshControl (Blocks)
@dynamic actionBlock;
- (id)initWitActionBlock: (void (^)())actionBlock {
self = [super init];
if (self) {
self.actionBlock = [actionBlock copy];
[self addTarget:self action:@selector(fireActionBlock) forControlEvents:UIControlEventValueChanged];
}
return self;
}
- (void)fireActionBlock {
self.actionBlock();
}
- (id)actionBlock{
return objc_getAssociatedObject(self, ActionBlockKey);
}
- (void)setActionBlock:(void (^)())actionBlock{
objc_setAssociatedObject(self, ActionBlockKey, actionBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
@end