[英]Memory Leak in iOS swift 3
I have recently started Swift and learning Memory Management . 我最近开始学习Swift并学习内存管理 。 And I am unable to solve this issue of memory leak.
我无法解决此内存泄漏问题。
This is my model class: 这是我的模型课:
class Contact {
var name: String?
var age: String?
weak var address: Address?
deinit {
print("Contact Delloacated")
}
}
class Address {
var address: String?
}
I am using this model in my controller. 我在控制器中使用此模型。
class Controller: UIViewController {
var contacts: [Contact]()?
fetchContact() {
let path = "some url"
let url = URL(string: path)
let session = URLSession.shared
let task = session.dataTask(with: url!) { [weak self] (data,
response, error) in
if error != nil {
print(error!)
return
}
if let data = data {
do {
let jsonResult = try JSONSerialization.jsonObject(with:
data, options: .mutableContainers)
self?.contacts = [Contact]()
let contact = Contact()
// do some operation to get required data and append
//into contactList array
self?.append?.append(contact)
}
override func viewDidLoad() {
super.viewDidLoad()
fetchContact()
}
}
Although I have used weak for Address in Contact model and used "[weak self]" in closure of "fetchContact()" method in controller while fetching data to avoid retain cycle. 尽管我在Contact模型中对Address使用了weak ,并且在控制器中为获取数据以避免保留周期时在控制器的“ fetchContact()”方法的关闭中使用了“ [weak self]”。 But still I got memory leak warning in line : "self?.append?.append(contact)".
但是我仍然在行中收到内存泄漏警告: “ self?.append?.append(contact)”。 I observed the leak from instrument in Xcode 8.3.3.
我在Xcode 8.3.3中观察到仪器泄漏。
I am confused why there is still strong reference of Contact in controller class. 我很困惑,为什么控制器类中仍然有Contact的强大参考。
In your case you are using for loop for parsing dictionary. 在您的情况下,您正在使用for循环来解析字典。 So , you can release memory inside for loop by using
autorelease
因此,您可以使用
autorelease
循环内的内存
Write this inside for loop , this will release memory everytime loop is called. 将此内容写入for循环中,这将在每次调用循环时释放内存。
autoreleasepool {
/* code */
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.