Does the following Contact
class in the code below generate strong reference cycle if the lazy property is not accessed?
When I use the "Debug Memory Graph" feature of Xcode, I cannot find any leaks when the lazily initialised property is either accessed or ignored. Is this correct?
What's the recommended practice for referencing self
when initialising variables and property with functions?
Thanks!
import Foundation
class Contact {
let identifier = UUID().uuidString
lazy var photo: Data = {
// Get the URL to the /path/to/app/sandbox/Caches folder.
guard let folderURL = try? FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) else {
return Data()
}
// Get the URL to a specific png in the Caches folder.
let fileURL = folderURL.appendingPathComponent(self.identifier).appendingPathExtension("png")
if let data = try? Data(contentsOf: fileURL) {
return data
}
// Failing this, return an empty data instance.
return Data()
}()
}
// When memory used by this function is cleared, I would expect contact to be deinitialised, because the property has been accessed and therefore initialised.
func lazyVarAccessed() {
let contact = Contact()
let data = contact.photo
print("\(data)")
}
// The photo property is not accessed and by virtue of being lazy, not initialised. Is contact deinitialised when the memory used by this function is cleared?
func lazyVarIgnored() {
let contact = Contact()
print("\(contact)")
}