几天后,我仍然无法找出为什么使用 executeFetchRequest
会导致小的内存泄漏,显示在 Instruments: Leaks 中。我完全知道 UIKit 有很多漏洞,但我想至少尝试更好地理解它。
每当我执行获取请求时,只要我不将其分配给类属性,它就不会泄漏。为了更好地解释这一点,我创建了一个新项目,如下所示:
class TestViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!
var persons = [Persons]()
override func viewDidLoad() {
super.viewDidLoad()
let request = NSFetchRequest(entityName: "Persons")
let results = context.executeFetchRequest(request, error: nil) as! [Persons]
persons = results //If I comment out this line, no leak will occur
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return persons.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = persons[indexPath.row].name
return cell
}
}
在我更改为此 ViewController 后,大约 10 秒后 Instruments 中将出现泄漏(请参见下面的屏幕截图)。
经过更多测试后,创建 outlet collection
也会导致轻微泄漏。找了几天,遇到同样问题的人不多。我想知道我是不是做错了什么,还是应该忽略它?泄漏的大小并没有那么大(大约 100 字节)。
最佳答案
关于 socket 集合泄漏内存的问题, 见this answer .
如 Joe Collins 所述,解决方法是:
“...用 NSArray! 替换 [UIButton]! 并在稍后使用时将其内容转换为 UIButton。”
关于swift - CoreData 或 Outlet 集合的轻微泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30086044/