I have subclasses of UINavigationController
and UITableViewController
.
To initialize subclasses I decided to use some convenience init
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.