【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
相关文章推荐
- iOS - 使用"Masonry"库做约束(自动布局)
- 根据Facebook内存的管理使用,浅谈在iOS上自动检测内存泄漏问题
- 根据Facebook内存的管理使用,浅谈在iOS上自动检测内存泄漏问题
- 解决了一个隐蔽的内存泄漏——pthread_create后没有detach导致内存持续增长
- [百度分享]频繁分配释放内存导致的性能问题的分析
- [SQL Server] 数据库日志文件自动增长导致连接超时的分析
- 【百度分享】频繁分配释放内存导致的性能问题的分析
- Linux开发心得总结2 - 频繁分配释放内存导致的性能问题的分析
- .NET----使用母版页后,控件名称自动生成导致js无法正常操作.net控件的问题
- Linux_Swap持续增长的问题(tcpdump引入,与使用方法)
- [SQL Server] 数据库日志文件自动增长导致连接超时的分析
- 频繁分配释放内存导致的性能问题的分析
- 频繁分配释放内存导致的性能问题的分析
- 使用PrintWriter对象导致Struts国际化化失败问题的解决及分析
- iOS内存暴增问题追查与使用陷阱 推荐
- 使用母版页后,控件名称自动生成导致js无法正常操作.net控件的问题
- 百度分享]频繁分配释放内存导致的性能问题的分析
- 【百度分享】频繁分配释放内存导致的性能问题的分析
- session不及时释放导致内存溢出的性能问题分析
- iOS内存暴增问题追查与使用陷阱