UIControl 如何管理它的目标?

Posted

技术标签:

【中文标题】UIControl 如何管理它的目标?【英文标题】:How does UIControl manage its target? 【发布时间】:2015-09-26 04:42:15 【问题描述】:

苹果:

// the action cannot be NULL. Note that the target is not retained.
- (void)addTarget:(nullable id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;

请注意,不保留目标。

在 UIControl+BlocksKit.m 中

BKControlWrapper *target = [[BKControlWrapper alloc] initWithHandler:handler forControlEvents:controlEvents];
[handlers addObject:target];
[self addTarget:target action:@selector(invoke:) forControlEvents:controlEvents];

那么UIControl如何管理目标,为什么目标没有释放?

【问题讨论】:

UIControl 目标没有被释放,因为它没有被保留。 【参考方案1】:

bk_addEventHandler:forControlEvents: 方法通过将BKControlWrapper 实例添加到NSMutableSet 来保留它。该集合由events 字典保留,该字典由控件本身保留,因为该字典使用OBJC_ASSOCIATION_RETAIN_NONATOMIC 与控件关联。

重要的是您传递给bk_addEventHandler:forControlEvents: 的块不会创建保留循环。为此,您必须确保块在需要时使用弱引用(例如,如果它需要引用视图控制器而不是引用控件)。

【讨论】:

以上是关于UIControl 如何管理它的目标?的主要内容,如果未能解决你的问题,请参考以下文章

如何修改 UIControl 框架

UIControl.appearance().addTarget 停止在 Swift 4 上工作

如何正确子类UIControl?

突出显示 UIControl 子类

如何使 UIControl 在 XCUITest 中显示为按钮?

目标 C:标签文本(UIControl 的子类)未显示在 UITableview 中