简体   繁体   中英

Swift How to return child object that keeps parent object as long as child lives in memory

I consider whether it is possible to return from function child object created inside parent object that will keep reference to its parent and prevent parent from being deallocated from memory. Simultaneously I don't want to have retain cycle and memory leak.

class ObjectA { 
   let objectB = ObjectB()
}

class ObjectB { 

}

func factoryFunc() -> ObjectB { 
   ObjectA().objectB
}

Client code

let objB = factoryFunc() 
// but keep also ObjectA as long as objB lives 
// but do not create retain cycle
// I do not want to return ObjectA and do not want to manage it outside of black box factory method. 

I could add

class ObjectB { 
    var parent: ObjectA?
}

It creates retain cycle and memory leak

class ObjectB { 
        weak var parent: ObjectA?
    }

This doesn't prevent deallocation of ObjectA

There would be no other way than by creating a strong reference cycle. But if you reach this, there might be an issue in the design; you should never be needed to create a strong reference cycle. In your case:

  1. Maybe you should not use ObjectB directly, but rather through some designed interface of ObjectA .

  2. If you need only ObjectB specifically, then you don't need ObjectA .

  3. If ObjectA is so important in your application, then you should manage it outside of that factory.

If you don't need to use ObjectA (as you don't want it returned), and you won't manage it outside that scope, then you certainly don't need it at all and you will be able to move your logic outside that class (or maybe inherit ObjA in ObjB ).

If you need it in some other hidden way anyways, then you should create some kind of controller or manager that manages this whole flow where you use the classes.

Also, very important, keep in mind that the ownership must go only one way, never both ways, and, almost always, the control flow in the same way as the ownership. If ObjectA is the parent of ObjectB , then ObjectB should know absolutely nothing about ObjectA .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM