是否可以传递一个 Objective-C 块@selector
论证中的一个UIButton
?即,有什么办法可以让以下工作发挥作用吗?
[closeOverlayButton addTarget:self
action:^ {[anotherIvarLocalToThisMethod removeFromSuperview];}
forControlEvents:UIControlEventTouchUpInside];
Thanks
是的,但是您必须使用类别。
就像是:
@interface UIControl (DDBlockActions)
- (void) addEventHandler:(void(^)(void))handler
forControlEvents:(UIControlEvents)controlEvents;
@end
实现会有点棘手:
#import <objc/runtime.h>
@interface DDBlockActionWrapper : NSObject
@property (nonatomic, copy) void (^blockAction)(void);
- (void) invokeBlock:(id)sender;
@end
@implementation DDBlockActionWrapper
@synthesize blockAction;
- (void) dealloc {
[self setBlockAction:nil];
[super dealloc];
}
- (void) invokeBlock:(id)sender {
[self blockAction]();
}
@end
@implementation UIControl (DDBlockActions)
static const char * UIControlDDBlockActions = "unique";
- (void) addEventHandler:(void(^)(void))handler
forControlEvents:(UIControlEvents)controlEvents {
NSMutableArray * blockActions =
objc_getAssociatedObject(self, &UIControlDDBlockActions);
if (blockActions == nil) {
blockActions = [NSMutableArray array];
objc_setAssociatedObject(self, &UIControlDDBlockActions,
blockActions, OBJC_ASSOCIATION_RETAIN);
}
DDBlockActionWrapper * target = [[DDBlockActionWrapper alloc] init];
[target setBlockAction:handler];
[blockActions addObject:target];
[self addTarget:target action:@selector(invokeBlock:) forControlEvents:controlEvents];
[target release];
}
@end
一些解释:
- 我们正在使用一个名为“仅限内部”的自定义类
DDBlockActionWrapper
。这是一个简单的类,具有一个块属性(我们想要调用的块)和一个简单调用该块的方法。
- The
UIControl
类别只是实例化这些包装器之一,为其提供要调用的块,然后告诉自己使用该包装器及其invokeBlock:
方法作为目标和操作(正常)。
- The
UIControl
类别使用关联对象来存储数组DDBlockActionWrappers
, 因为UIControl
不保留其目标。该数组用于确保块在应该被调用时存在。
-
我们必须确保DDBlockActionWrappers
当对象被销毁时被清理,所以我们正在做一个令人讨厌的 swizzling out 的黑客攻击-[UIControl dealloc]
使用一个新的对象来删除关联的对象,然后调用原始对象dealloc
代码。棘手,棘手。 事实上,关联对象在释放期间会自动清理 http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocAssociativeReferences.html#//apple_ref/doc/uid/TP30001163-CH24-SW3.
最后这段代码是在浏览器中输入的,并没有被编译。可能有一些问题。你的旅费可能会改变。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)