ios – CoreData generated class – Is there reminiscence leak threat of not utilizing weak in inverse relationship?


When come to round reference, it comes with threat of reminiscence leaking, by not utilizing a weak key phrase. For example :-


Reminiscence leak with out utilizing 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("begin of scope")

if true {
    let pet = Pet()
    let human = Human(pet)
    pet.human = human
    
    print("going to finish of scope")
}

print("finish of scope")

/*
 Output:
 
 begin of scope
 going to finish of scope
 finish of scope
 */

No reminiscence leak by utilizing 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("begin of scope")

if true {
    let pet = Pet()
    let human = Human(pet)
    pet.human = human
    
    print("going to finish of scope")
}

print("finish of scope")

/*
 Output:
 
 begin of scope
 going to finish of scope
 bye bye from Human
 bye bye from Pet
 finish of scope
 */

In CoreData, when setup 2 entities with one-to-many relationship, it is strongly recommended to have inverse relationship too. Therefore, CoreData will generate the next class with round reference.

extension NSHolidayCountry {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<NSHolidayCountry> {
        return NSFetchRequest<NSHolidayCountry>(entityName: "NSHolidayCountry")
    }

    @NSManaged public var code: String
    @NSManaged public var identify: 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 identify: String
    @NSManaged public var holidayCountry: NSHolidayCountry?

}

enter image description here

(One to many relationship present in entity NSHolidayCountry)


enter image description here

(One to One inverse relationship present in entity NSHolidaySubdivision)


NSHolidaySubdivision is having inverse relationship to NSHolidayCountry.

Nevertheless, such inverse relationship shouldn’t be marked as weak, primarily based on CoreData generated class.

I used to be questioning, does this include a reminiscence leak threat? Ought to I, add a weak key phrase manually in entity NSHolidaySubdivision's holidayCountry ?

Leave a Reply