"Ambiguous reference to member 'init(...)" calling baseclass initializer - ios

I have a baseclass:
class ViewController: UIViewController
{
init(nibName nibNameOrNil: String?)
{
super.init(nibName: nibNameOrNil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) { }
}
a subclass:
class OneViewController: ViewController
{
private var one: One
init(one: One)
{
self.one = one
super.init(nibName: "OneNib")
}
required init?(coder aDecoder: NSCoder) { }
}
and a subclass of the above subclass:
class TwoViewController: OneViewController
{
private var two: Two
init(two: Two)
{
self.two = two
super.init(nibName: "TwoNib") <== ERROR
}
required init?(coder aDecoder: NSCoder) { }
}
At the indicated line I get the error:
Ambiguous reference to member 'init(one:)'
I don't understand why the compiler can't figure out I'm referring to ViewController's init(), like it managed to do in One's init().
What am I missing and/or doing wrong?

I don't understand why the compiler can't figure out I'm referring to ViewController's init(), like it managed to do in One's init()
It is because, from inside TwoViewController, the compiler can't see ViewController's init. The rule is:
As soon as you implement a designated initializer, you block inheritance of initializers.
Therefore, OneViewController has only one initializer, namely init(one:). Therefore, that is the only super initializer that TwoViewController can call.
If you want ViewController's init(nibName:) to be present in OneViewController, you must implement it in OneViewController (even if all it does is to call super).

The chapter in the Swift manual on Designated Initializers will clarify it, but basically OneViewController has only one way to set self.one, and that's by initialising using init(one: One). You cannot bypass that, which is what you are trying to do.
If what you were trying to do could succeed, what value would two.one have in the following?
let two = Two(two: SomeTwo)
print(two.one)
Answer - undefined. That's why it isn't allowed.
Having declared One.init(one:) it is now the Designated Initializer, and there's no way to go round it.

you don't necessary pass value into constructor's ViewController . you can define public object in oneViewController and you access of outer .
class OneViewController: ViewController {
public var one: One
}
let vc = storyboard?.instantiateViewControllerWithIdentifier("OneViewController") as OneViewController
let one = One()
vc.one = one

Related

Where is the default init for UIViewController?

So I've recently run into this issue where some Swift 5 code I've written compiles in Xcode 11.0 but not 11.2.1, and the latter complained that there was no default initializer for my class extending UIViewController (it defines no initializers) when I try to instantiate it.
Indeed, when I look at the definition for UIViewController, these are the only two definitions:
public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)
public init?(coder: NSCoder)
It also contains a comment which seems to imply there should be a default initializer present as well, but I can't find it.
/*
The designated initializer. If you subclass UIViewController, you must call the super implementation of this
method, even if you aren't using a NIB. (As a convenience, the default init method will do this for you,
and specify nil for both of this methods arguments.) In the specified NIB, the File's Owner proxy should
have its class set to your view controller subclass, with the view outlet connected to the main view. If you
invoke this method with a nil nib name, then this class' -loadView method will attempt to load a NIB whose
name is the same as your view controller's class. If no such NIB in fact exists then you must either call
-setView: before -view is invoked, or override the -loadView method to set up your views programatically.
*/
I've found a workaround to make this work, I just have to define all three initializers calling into the superclass initializers, with the default working as described in the comment, but I'm still perplexed how I've gotten away with using the default initializer all this time when I can't find it anywhere. Where is the default initializer described in the comment actually defined?
Normally this thing happens when you define a variable and do not initialize it. So if there is such variable in you code like-
var name:string
change it like
var name:string = ""
or
var name = string()
You cant find init() decladation because it is a convenience initializer.
When you attempt to override it Xcode will give you this error:
Initializer does not override a designated initializer from its superclass
and this message:
Attempt to override convenience initializer here (UIKit.UIViewController)
And you cant override the convenience initializers in Swift, and the convenience initializer must call one of the self.init’s not one of the superclass.
convenience init() {
self.init(nibName: nil, bundle: nil)
}
You can call init() as default constructor.
import UIKit
class InstantWebViewController: UIViewController {
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init() {
super.init(nibName: nil, bundle: nil)
}
init(_ object: [String: Any?]?) {
}
}

Swift: 'super.init' isn't called on all paths before returning from initializer?

I am getting this error on the last brace of a init in a class of mine. The class looks something like the following (I market the spot where error happens):
class RecordingViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {
let cameraButton:UIButton?
let camPreview:UIView?
init (cameraButton: UIButton!, camPreview: UIView!) {
self.cameraButton = cameraButton
self.camPreview = camPreview
} //get error here
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//do a bunch of other stuff
}
I have looked here and here for a solution but both seem like solutions that are either really bad or that are too specific to that question, thus they have not work for me.
I was hoping for a solution to my problem done in such a way that it can help me understand why this error is happening.
Since you inherit from UIViewController, you should call super.init right after you set the variables in your init function
When you inherit a class and implement a new init function or override its own init function you should (almost) always call super.init. Let's take your example, you inherited from UIViewController. UIViewController has a few init functions that you can use to initialize a view controller. if you don't call super.init, all the code inside those functions will not get called and possibly the view controller won't get initialized.
Anyway, this piece of code should work for you:
class ViewController: UIViewController {
var button: UIButton?
init(button: UIButton) {
self.button = button
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Here is what I found on Swift Programming Language:
In the first phase, each stored property is assigned an initial value by the class that introduced it. Once the initial state for every stored property has been determined, the second phase begins, and each class is given the opportunity to customize its stored properties further before the new instance is considered ready for use.
A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.
Hope this can explain that question.

Why must I keep declaring the same required but not implemented initializer for init(coder aDecoder) for my programatic UIViewController subclass?

Perhaps it is just me, but I find certain aspects of swift... obtuse to say the least.
I don't use Interface Builder most of the time because I like using PureLayout. So I was hoping to make a UIViewController subclass, say PureViewController, that had a handy init without parameters:
class PureViewController : UIViewController {
init() {
super.init(nibName: nil, bundle: nil)
}
}
But this is not okay, for XCode tells me I must also implement init(coder aDecoder: NSCoder). Okay, that's fine! That's why I made this class - so I don't have to do this again for subclasses.
class PureViewController : UIViewController {
init() {
super.init(nibName: nil, bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Ok, now here's what I don't get.
I define a subclass, SomePureViewController : PureViewController, with an initializer init(viewModel:ICrackersViewModel)...
class SomePureViewController : PureViewController {
init(viewModel:ICrackersViewModel) {
super.init()
}
}
But it STILL wants me to define the same stupid initializer till kingdom come!
class SomePureViewController : PureViewController {
init(viewModel:ICrackersViewModel) {
super.init()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Now I understand the idea - there is no init(decoder) in my subclass, even though it is defined in its parent class.
Maybe I've always dealt with this issue with UIViewController and never noticed it before.
My questions are as follows:
Is there something I am doing wrong to cause this behavior?
Is there any way outside of inheritance that I can avoid repeating myself?
Are there plans to any plans to change this?
The point is that one can initialize a possibly derived class just by knowing the base type.
Lets assume a base class
class Base {
let value: Int
required init(value: Int) {
self.value = value
}
}
and a function
func instantiateWith5(cls: Base.Type) -> Base {
return cls.init(value: 5)
}
then we can do
let object = instantiateWith5(Base.self)
Now if someone defines a derived class
class Derived: Base {
let otherValue: Int
init() {
otherValue = 1
super.init(value: 1)
}
required init(value: Int) {
fatalError("init(value:) has not been implemented")
}
}
We are at least able to call
let object2 = instantiateWith5(Derived.self)
violating LSP, but that's a problem of your code, not the language.
Swift has to guarantee that initializers leave your objects in a initialized state, even when they are derived from a base object, so I guess changing that would be a bad thing. If you like to define a UIViewController that is not deserializable and thereby violating LSP it's your decision - but don't expect the language to support you in this.
I think that this is swift issue and there is no way how to avoid this. We all hate this empty - fatal error initializer.
As the initialiser is marked with the required keyword, all subclasses must implement that initialiser and they must also specify required on their implementation so that their subclasses are also required to implement it.
Required Initializers
Write the required modifier before the
definition of a class initializer to indicate that every subclass of
the class must implement that initializer
You must also write the required modifier before every subclass implementation of a required initializer, to indicate that the initializer requirement applies to further subclasses in the chain.”
This has been part of the Swift language since 1.0 and it is unlikely to change.
The issue is actually to do with the use of the required keyword in the UIViewController class definition. In theory this could be changed, but again I think it is unlikely.

How To Init A UIView That Exists In Interface Builder But Also Requires Init In Code

Here is my view class
class V_TakePhoto:UIView{
var _takePhotoCallback:(iImage)->Void?
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
_takePhotoCallback = nil
}
#IBAction func takePhoto(sender: AnyObject) {
println("Here we go!")
}
func initWithCameraCallback((iImage)->Void)
{
}
}
This class is a UIView subclass. In the interface builder I selected the ViewController class, and then selected its View object. I assigned V_TakePhoto to this view object.
In the ViewController class, which I assigned to C_TakePhoto class, I want to init the V_TakePhoto class.
As you can see, I want it to have a callback variable that it gets passed at run time. However, because the view is already getting initialized from the interface builder, init(coder) is getting called first.
As it stands right now it seems hacky that I need to have 2 init functions. One where interface builder calls it, then again when my ViewController inits the view with its callback. Also I will have a number of variables, and I need to pre-init them in the init(coder) call then RE-init them again when the ViewController calls the 'true' init on the V_PhotoClass. Seems very hacky to me, there must be a clean 'correct' way to do this.
Can you suggest a cleaner way to handle a situation where you have variables and need to init a view despite there being an init(coder) call from the interface builder?
I would suggest creating a function in V_TakePhoto and call it in both V_TakePhoto's init(coder) and ViewController's viewDidLoad(), something like :
In V_TakePhoto :
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
specialInit()
}
func specialInit() {
// some of your view initialization
}
In your View Controller :
#IBOutlet weak var takePhotoView: V_TakePhoto!
override func viewDidLoad() {
super.viewDidLoad()
// this method is called after the view controller has loaded its view hierarchy into memory.
takePhotoView.specialInit() // RE-init
}

How to subclass UITableViewController in Swift

I want to subclass UITableViewController and be able to instantiate it by calling a default initializer with no arguments.
class TestViewController: UITableViewController {
convenience init() {
self.init(style: UITableViewStyle.Plain)
}
}
As of the Xcode 6 Beta 5, the example above no longer works.
Overriding declaration requires an 'override' keyword
Invalid redeclaration of 'init()'
NOTE This bug is fixed in iOS 9, so the entire matter will be moot at that point. The discussion below applies only to the particular system and version of Swift to which it is explicitly geared.
This is clearly a bug, but there's also a very easy solution. I'll explain the problem and then give the solution. Please note that I'm writing this for Xcode 6.3.2 and Swift 1.2; Apple has been all over the map on this since the day Swift first came out, so other versions will behave differently.
The Ground of Being
You are going to instantiate UITableViewController by hand (that is, by calling its initializer in code). And you want to subclass UITableViewController because you have instance properties you want to give it.
The Problem
So, you start out with an instance property:
class MyTableViewController: UITableViewController {
let greeting : String
}
This has no default value, so you have to write an initializer:
class MyTableViewController: UITableViewController {
let greeting : String
init(greeting:String) {
self.greeting = greeting
}
}
But that's not a legal initializer - you have to call super. Let's say your call to super is to call init(style:).
class MyTableViewController: UITableViewController {
let greeting : String
init(greeting:String) {
self.greeting = greeting
super.init(style: .Plain)
}
}
But you still can't compile, because you have a requirement to implement init(coder:). So you do:
class MyTableViewController: UITableViewController {
let greeting : String
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(greeting:String) {
self.greeting = greeting
super.init(style: .Plain)
}
}
Your code now compiles! You now happily (you think) instantiate this table view controller subclass by calling the initializer you wrote:
let tvc = MyTableViewController(greeting:"Hello there")
Everything looks merry and rosy until you run the app, at which point you crash with this message:
fatal error: use of unimplemented initializer init(nibName:bundle:)
What Causes the Crash and Why You Can't Solve It
The crash is caused by a bug in Cocoa. Unknown to you, init(style:) itself calls init(nibName:bundle:). And it calls it on self. That's you - MyTableViewController. But MyTableViewController has no implementation of init(nibName:bundle:). And does not inherit init(nibName:bundle:), either, because you already provided a designated initializer, thus cutting off inheritance.
Your only solution would be to implement init(nibName:bundle:). But you can't, because that implementation would require you to set the instance property greeting - and you don't know what to set it to.
The Simple Solution
The simple solution - almost too simple, which is why it is so difficult to think of - is: don't subclass UITableViewController. Why is this a reasonable solution? Because you never actually needed to subclass it in the first place. UITableViewController is a largely pointless class; it doesn't do anything for you that you can't do for yourself.
So, now we're going to rewrite our class as a UIViewController subclass instead. We still need a table view as our view, so we'll create it in loadView, and we'll hook it up there as well. Changes are marked as starred comments:
class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // *
let greeting : String
weak var tableView : UITableView! // *
init(greeting:String) {
self.greeting = greeting
super.init(nibName:nil, bundle:nil) // *
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() { // *
self.view = UITableView(frame: CGRectZero, style: .Plain)
self.tableView = self.view as! UITableView
self.tableView.delegate = self
self.tableView.dataSource = self
}
}
Also you'll want, of course, to add the minimal required data source methods. We now instantiate our class like this:
let tvc = MyViewController(greeting:"Hello there")
Our project compiles and runs without a hitch. Problem solved!
An Objection - Not
You might object that by not using UITableViewController we have lost the ability to get a prototype cell from the storyboard. But that is no objection, because we never had that ability in the first place. Remember, our hypothesis is that we are subclassing and calling our own subclass's initializer. If we were getting the prototype cell from the storyboard, the storyboard would be instantiating us by calling init(coder:) and the problem would never have arisen in the first place.
Xcode 6 Beta 5
It appears that you can no longer declare a no-argument convenience initializer for a UITableViewController subclass. Instead, you need to override the default initializer.
class TestViewController: UITableViewController {
override init() {
// Overriding this method prevents other initializers from being inherited.
// The super implementation calls init:nibName:bundle:
// so we need to redeclare that initializer to prevent a runtime crash.
super.init(style: UITableViewStyle.Plain)
}
// This needs to be implemented (enforced by compiler).
required init(coder aDecoder: NSCoder!) {
// Or call super implementation
fatalError("NSCoding not supported")
}
// Need this to prevent runtime error:
// fatal error: use of unimplemented initializer 'init(nibName:bundle:)'
// for class 'TestViewController'
// I made this private since users should use the no-argument constructor.
private override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
}
Props to matt for a great explanation. I've made use of both matt's and #Nick Snyder's solutions, however I ran into a case in which neither would quite work, because I needed to (1) initialize let fields, (2) use init(style: .Grouped) (without getting a runtime error), and (3) use the built-in refreshControl (from UITableViewController). My workaround was to introduce an intermediate class MyTableViewController in ObjC, then use that class as the base of my table view controllers.
MyTableViewController.h
#import <UIKit/UIKit.h>
// extend but only override 1 designated initializer
#interface MyTableViewController : UITableViewController
- (instancetype)initWithStyle:(UITableViewStyle)style NS_DESIGNATED_INITIALIZER;
#end
MyTableViewController.m:
#import "MyTableViewController.h"
// clang will warn about missing designated initializers from
// UITableViewController without the next line. In this case
// we are intentionally doing this so we disregard the warning.
#pragma clang diagnostic ignored "-Wobjc-designated-initializers"
#implementation MyTableViewController
- (instancetype)initWithStyle:(UITableViewStyle)style {
return [super initWithStyle:style];
}
#end
Add the following to Project's Bridging-Header.h
#import "MyTableViewController.h"
Then use in swift. Example: "PuppyViewController.swift":
class PuppyViewController : MyTableViewController {
let _puppyTypes : [String]
init(puppyTypes : [String]) {
_puppyTypes = puppyTypes // (1) init let field (once!)
super.init(style: .Grouped) // (2) call super with style and w/o error
self.refreshControl = MyRefreshControl() // (3) setup refresh control
}
// ... rest of implementation ...
}
I did it like this
class TestViewController: UITableViewController {
var dsc_var: UITableViewController?
override convenience init() {
self.init(style: .Plain)
self.title = "Test"
self.clearsSelectionOnViewWillAppear = true
}
}
Creating and displaying a instance of TestViewController in a UISplitViewController did work for me with this code.
Maybe this is bad practice, please tell me if it is (just started with swift).
For me there's still a problem when there are non optional variables and the solution of Nick Snyder is the only one working in this situation
There's just 1 problem:
The variables are initialized 2 times.
Example:
var dsc_statistcs_ctl: StatisticsController?
var dsrc_champions: NSMutableArray
let dsc_search_controller: UISearchController
let dsrc_search_results: NSMutableArray
override init() {
dsrc_champions = dsrg_champions!
dsc_search_controller = UISearchController(searchResultsController: nil)
dsrc_search_results = NSMutableArray.array()
super.init(style: .Plain) // -> calls init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) of this class
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
// following variables were already initialized when init() was called and now initialized again
dsrc_champions = dsrg_champions!
dsc_search_controller = UISearchController(searchResultsController: nil)
dsrc_search_results = NSMutableArray.array()
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
matt's answer is the most complete, but if you do want to use a tableViewController in the .plain style (say for legacy reasons). Then all you need to do is call
super.init(nibName: nil, bundle: nil)
instead of
super.init(style: UITableViewStyle.Plain) or self.init(style: UITableViewStyle.Plain)
I wanted to subclass UITableViewController and add a non-optional property which requires overriding the initializer and dealing with all the problems described above.
Using a Storyboard and a segue gives you more options if you can work with an optional var rather than a non-optional let in your subclass of UITableViewController
By calling performSegueWithIdentifier and overriding prepareForSegue in your presenting view controller, you can get the instance of the UITableViewController subclass and set the optional variables before initialization is completed:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "segueA"{
var viewController : ATableViewController = segue.destinationViewController as ATableViewController
viewController.someVariable = SomeInitializer()
}
if segue.identifier == "segueB"{
var viewController : BTableViewController = segue.destinationViewController as BTableViewController
viewController.someVariable = SomeInitializer()
}
}
I've noticed a similar error when using static tableview cells and you gotta implement this:
init(coder decoder: NSCoder) {
super.init(coder: decoder)
}
if you implement:
required init(coder aDecoder: NSCoder!) {
// Or call super implementation
fatalError("NSCoding not supported")
}
I was just getting a crash there... Kind of as expected. Hope this helps.
Not sure it is related to your question, but in case you want to init UITableView controller with xib, Xcode 6.3 beta 4 Release Notes provide a workaround:
In your Swift project, create a new empty iOS Objective-C file. This will trigger a sheet asking you “Would you like to configure an Objective-C bridging header.”
Tap “Yes” to create a bridging header
Inside [YOURPROJECTNAME]-Bridging-Header.h add the following code:
#import UIKit;
#interface UITableViewController() // Extend UITableViewController to work around 19775924
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil NS_DESIGNATED_INITIALIZER ;
#end
class ExampleViewController: UITableViewController {
private var userName: String = ""
static func create(userName: String) -> ExampleViewController {
let instance = ExampleViewController(style: UITableViewStyle.Grouped)
instance.userName = userName
return instance
}
}
let vc = ExampleViewController.create("John Doe")

Resources