Reputation: 6619
I would like to use an init
inside of my view controller in order to initialize some properties. I've tried creating a default init
and overriding the existing ones in UIViewController
, and everything compiles without error, but none of them get called. Why is that?
These are my current inits, none are called.
init(){
cameraSession = AVCaptureSession()
cameraSession.sessionPreset = AVCaptureSessionPresetLow
captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) as AVCaptureDevice
super.init(nibName: nil, bundle: nil)
}
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: Bundle!) {
cameraSession = AVCaptureSession()
cameraSession.sessionPreset = AVCaptureSessionPresetLow
captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) as AVCaptureDevice
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
cameraSession = AVCaptureSession()
cameraSession.sessionPreset = AVCaptureSessionPresetLow
captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) as AVCaptureDevice
super.init(coder: aDecoder)
}
Upvotes: 1
Views: 65
Reputation: 1755
Instead of using an initialiser, try initialising the properties with default values using the design-and-call pattern (see http://www.apeth.com/swiftBook/ch02.html#SECdefineandcall and http://www.apeth.com/swiftBook/ch03.html#_computed_initializer), like this:
class ViewController {
var cameraSession: AVCaptureSession = {
let session = AVCaptureSession()
session.sessionPreset = AVCaptureSessionPresetLow
return session
}()
var captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) as AVCaptureDevice
}
Then there's no need for an initialiser at all!
Upvotes: 0
Reputation: 39988
It depends upon how you're creating your view controller object.
If you're using storyboard or xib then this method will be called
required init?(coder aDecoder: NSCoder) {
}
Upvotes: 2