我有一个自定义的 UICollectionViewCell。左右滚动时(水平方向的UICollectionView)每次增加0.2MB内存占用。
我相信我在单元格对象中正确地实现了 prepareForReuse();在其中我删除了单元格的所有 subview 。
在我的 Collection View 单元格上使用对象的 didSet,我在我的单元格中调用 setupViews()。我添加了一个带有约束的 UIImageView 并将其添加为 subview 。这很好。
但是,当我使用 UILabel() 时,似乎出现了内存泄漏。当我查看 Instruments 时,我可以看到:VM: UILabel (CALayer) 每次在两个单元格之间滚动时都会重复创建! UIImageView 不会发生这种情况。
以防万一它是相关的,这是我的单元格中的 prepareForReuse 方法:
override func prepareForReuse() {
super.prepareForReuse()
self.moreButtonDelegate = nil
for subview in subviews {
subview.removeConstraints(subview.constraints)
subview.removeFromSuperview()
}
self.removeFromSuperview() // BURN EVERYTHING
}
这是我的代码:
private func setupViews() -> Void {
let imageView = myImageView // A lazy class property returns this
innerView.addSubview(imageView) // innerView is just another UIView within this cell
// Now I add constraints for imageView
}
因此,没有内存泄漏。看起来 ARC 正确地清理了所有内容,因为即使是图像,内存使用也不会呈指数增长。
但是,当我在 imageView 下面添加它时...
let address = UILabel()
address.translatesAutoresizingMaskIntoConstraints = false
address.text = "TEST"
address.font = UIFont.systemFont(ofSize: 22)
address.adjustsFontSizeToFitWidth = true
// Then I add constraints
我得到一个新的 VM: UILabel (CALayer) 行出现在单元格之间的每个滚动中,因此内存使用量跳跃。看一看:
我做错了什么?我正在使用 Xcode 9、iOS 11.2 模拟器。
最佳答案
我不确定这会解决您的特定问题,但我相信您误解了 prepareForReuse 并且我认为这很可能是您的代码有问题的地方。因此,让我们看一下您的实现:
override func prepareForReuse() {
super.prepareForReuse()
self.moreButtonDelegate = nil
for subview in subviews {
subview.removeConstraints(subview.constraints)
subview.removeFromSuperview()
}
self.removeFromSuperview() // BURN EVERYTHING
}
我相信您对 prepareForReuse 的看法完全错误。重用的要点是减少创建cell的 View (对象实例化、创建 View 层级、布局等)带来的开销。你不想烧掉一切!相反,您希望尽可能多地保留 contentView。理想情况下,您将只更改 View 的内容(即:UILabel 中的 text,UIImageView 中的 image,等),或者一些属性(backgroundColor 等)。
您可以使用 prepareForReuse 来取消您开始呈现单元格的一些重量级操作,但是当单元格从 View 中移除并且应该在其他地方重用时,这些操作可能还没有结束。例如,当您从 Web 下载内容时,用户可能会快速滚动,并且在下载和显示 Web 图像之前单元格会离开屏幕。现在,如果单元格被重复使用,则很可能会显示旧的下载图像 - 因此在 prepareForReuse 中,您可以取消此操作。
结论 - 我相信你在 prepareForReuse 中所做的操作都没有真正帮助 - 反之亦然,因为 Collection View 将不得不再次重新创建单元格的整个 UI从头开始(这意味着对象实例化等的所有开销)。我给你的第一个建议是放弃整个 prepareForReuse 实现。
其次,在您放弃 prepareForReuse 实现后,重构单元格,以便它只创建一次 UI,最好是在它的 initializer 中:
class UI: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupViews()
}
}
然后,在 cellForItemAt 中配置它的内容,这意味着为标签设置文本,为 ImageView 设置图像等。
最后,请记住 documentation 是什么说到它(我自己强调):
Performs any clean up necessary to prepare the view for use again.
只做真正需要做的事,一事不做。
在过去的一年里,我实现了许多tableView 和collectionView 数据源,但我真的只需要使用两次prepareForReuse(例如带有我上面提到的图片下载)。
编辑
我的意思的例子:
struct Model {
var name: String = ""
}
class CustomCell: UITableViewCell {
// create it once
private let nameLabel = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// setup view once
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupViews() {
// add it to view
self.contentView.addSubview(nameLabel)
// setup configuration
nameLabel.textColor = UIColor.red
// lay it out
nameLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
nameLabel.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 8),
nameLabel.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: -8),
nameLabel.leftAnchor.constraint(equalTo: self.contentView.leftAnchor, constant: 8),
nameLabel.rightAnchor.constraint(equalTo: self.contentView.rightAnchor, constant: -8),
])
}
// this is what you call in cellForRowAt
func configure(for model: Model) {
nameLabel.text = model.name
// someImageView.image = model.image
// etc.
}
override func prepareForReuse() {
super.prepareForReuse()
// if it is super important, reset the content, cancel operations, etc., but there is no reason to recreate the UI
// so e.g. this might be ok (although in this case completely unnecessary):
nameLabel.text = nil
// but you definitely don't want to do this (that's done once at the cell initialization):
// nameLabel = UILabel()
// setupViews()
}
}
class CustomTableViewController: UITableViewController {
var models: [Model] = [Model(name: "Milan")]
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(CustomCell.self, forCellReuseIdentifier: "customCell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return models.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomCell
// you just want to set the contents, not to recreate the UI components
cell.configure(for: models[indexPath.row])
return cell
}
}
Moreover, always work with cell's contentView, not directly with the cell. Notice that I used this:
self.contentView.addSubview(nameLabel)
而不是这个:
self.addSubview(nameLabel)
The content view of a UITableViewCell object is the default superview for content displayed by the cell. If you want to customize cells by simply adding additional views, you should add them to the content view so they will be positioned appropriately as the cell transitions into and out of editing mode.
关于ios - 使用 UILabel 时自定义 UICollectionViewCell 和内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48330547/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t