When come to circular reference, it comes with risk of memory leaking, by not using a weakkeyword. For instance :-
Memory leak without using weak
class Human {
deinit {
print("bye bye from Human")
}
init(_ pet: Pet) {
self.pet = pet
}
let pet: Pet
}
class Pet {
deinit {
print("bye bye from Pet")
}
var human: Human?
}
print("start of scope")
if true {
let pet = Pet()
let human = Human(pet)
pet.human = human
print("going to end of scope")
}
print("end of scope")
/*
Output:
start of scope
going to end of scope
end of scope
*/
No memory leak by using weak
class Human {
deinit {
print("bye bye from Human")
}
init(_ pet: Pet) {
self.pet = pet
}
let pet: Pet
}
class Pet {
deinit {
print("bye bye from Pet")
}
weak var human: Human?
}
print("start of scope")
if true {
let pet = Pet()
let human = Human(pet)
pet.human = human
print("going to end of scope")
}
print("end of scope")
/*
Output:
start of scope
going to end of scope
bye bye from Human
bye bye from Pet
end of scope
*/
In CoreData, when setup 2 entities with one-to-many relationship, it is recommended to have inverse relationship too. Hence, CoreData will generate the following class with circular reference.
extension NSHolidayCountry {
@nonobjc public class func fetchRequest() -> NSFetchRequest<NSHolidayCountry> {
return NSFetchRequest<NSHolidayCountry>(entityName: "NSHolidayCountry")
}
@NSManaged public var code: String
@NSManaged public var name: String
@NSManaged public var holidaySubdivisions: NSOrderedSet
}
extension NSHolidaySubdivision {
@nonobjc public class func fetchRequest() -> NSFetchRequest<NSHolidaySubdivision> {
return NSFetchRequest<NSHolidaySubdivision>(entityName: "NSHolidaySubdivision")
}
@NSManaged public var code: String
@NSManaged public var name: String
@NSManaged public var holidayCountry: NSHolidayCountry?
}
NSHolidaySubdivision
is having inverse relationship to NSHolidayCountry.
However, such inverse relationship is not marked as weak, based on CoreData generated class.
I was wondering, does this come with a memory leak risk? Should I, add a weak keyword manually in entity NSHolidaySubdivision's holidayCountry
?