Search code examples
swiftstructautomatic-ref-countingweak-references

Do i use [weak self] in URLSession dataTask when setting instance properties?


I'm not sure if i should use [weak self] here, do i have memory issue where i set the struct array if i don't?

URLSession.shared.dataTask(with: url) { (data, response, error) in

            if let error = error {
                self.showErrorAlertMessage(message: error.localizedDescription, title: "Some error")
                return
            }

            guard let data = data else { return }

            guard let httpResponse = response as? HTTPURLResponse else { return }

            if (httpResponse.statusCode == 200) {
                do {
                    let decodedResponse = try JSONDecoder().decode(CodableStruct.self, from: data)
                    self.structArray = decodedResponse.results
                } catch {
                    self.showErrorAlertMessage(message: error.localizedDescription, title: "Some error")
                    print("Error:\(error)")
                }
            } else {
                self.showErrorAlertMessage(message: "Some error", title: "error")
            }
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
            }.resume()
    }

Solution

  • Yes it's better to use [weak self] here.

    If you don't use, the block will hold a strong reference to self until it get called, so it might delay the release of self, but it won't cause a memory leak since self does not hold strong reference to this dataTask.