Convenience initialization of UINavigationController subclass makes subclass constant init twice

后端 未结 1 1588
别跟我提以往
别跟我提以往 2021-02-07 11:11

I have subclasses of UINavigationController and UITableViewController.

To initialize subclasses I decided to use some convenience init

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-07 12:11

    So this seems to be weirdly "expected behavior" with Swift. The reason it's happening is due to the constant initialized property service. Namely, this post summarizes the issue your seeing pretty well: blog post

    Essentially, the Obj-C underlying super classes are leaking memory and your service property is initialized twice because of this pattern of Obj-C initialization:

    - (id)init {
      self = [super init];
      if (self) {
        self = [[self.class alloc] initWithNibName:nil bundle:nil];
      }
      return self;
    }
    

    A simple solution to avoid this is the following pattern:

    import UIKit
    
    final class NavigationController: UINavigationController {
        var service: ObjectTest?
    
        convenience init() {
            self.init(rootViewController: UIViewController())
            self.service = ObjectTest("init nav")
        }
    }
    class ObjectTest: NSObject{
        init(_ string: String) {
            super.init()
            print(string)
        }
    }
    

    All that's changing from your implementation is initializing the service only after your class itself is initialized.

    Another solution, though, is to use the designated initializer for the superclass your initializing. Meaning that you don't use a convenience initializer which would employ the above Obj-C initialization pattern.

    0 讨论(0)
提交回复
热议问题