您的位置:首页 > 移动开发 > IOS开发

【iOS自动约束】使用Masonry导致内存持续增长问题分析

2016-09-05 17:26 686 查看

前言

看标题千万别误以为是Masonry自身原因导致内存问题,而是使用不当所致。

怎样用Masonry给视图添加约束?

通常情况下,我们会重写updateConstraints方法!

用一个tableView的自定义cell为例做个展示:

第一步,在初始化方法中加载子视图;

第二步,重写updateConstraints方法,在这个方法中给各个子视图添加约束。

第三步,在配置cell数据的方法中调用系统方法[self updateConstraintsIfNeeded]。

通过以上三步,一个cell就配置好了。接下来看看updateConstraints的内部实现:

- (void)updateConstraints {
[self.messageImageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.msgContentView).with.insets(UIEdgeInsetsMake(4, 4, 4, 12));
}];
[super updateConstraints];
}

其实,这样的写法是有问题的。

问题来了!

如果需要频繁配置cell的数据,那么updateConstraints会多次执行,每执行一次,内存就会增长一次。

怎么解决?

看看官方文档对updateConstraints的解释:

Custom views that set up constraints themselves should do so by overriding this method. When your custom view notes that a change has been made to the view that invalidates one of its constraints, it should immediately remove
that constraint, and then call setNeedsUpdateConstraints to note that constraints need to be updated. Before layout is performed, your implementation of updateConstraints will be invoked, allowing you to verify that all necessary constraints for your
content are in place at a time when your custom view’s properties are not changing.

标红的部分,重点说在对没用的或失效的约束应该立即删除。而Masonry的mas_makeConstraints方法是添加约束。每添加一层,内存增长一次,你不删除,它就一直在。

所以,问题就出在约束的管理上了。

Masonry提供了三种设置约束的方法,分别是

- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *))block
- (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *))block
- (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block
第一个是添加约束,不管原来与没有,只是个添加;

第二个是更新,在原来约束的基础上进行局部更新;

第三个是重设,删除原来已有的约束,重新添加约束,可以替换mas_remakeConstraints。

这下有解了。在cell约束需要频繁改变时(或者说updateConstraints会被多次调用时),我们要用mas_remakeConstraints方法来设置约束。为什么不用mas_updateConstraints呢,因为第一次设置约束时mas_updateConstraints代替不了mas_makeConstraints。大家也可以参考How
to Use updateConstraints
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: