问题
I want to subclass NSURLSession class, but I have problem with initialisation.
Basically I override the constructor and initialising the constant authUrl
there then calling the parent init method.
class NSURLAuthSession: NSURLSession {
let authUrl:NSURL;
//Error: Initializer does not override a designated initializer from its superclass
override init(configuration: NSURLSessionConfiguration, delegate: NSURLSessionDelegate?, delegateQueue queue: NSOperationQueue?){
self.authUrl = NSURL.URLWithBaseURLString("http://192.168.10.105:8888/api/v1", pathSegments: ["users", "login"])!
super.init(configuration: configuration, delegate: delegate, delegateQueue: queue)
}
}
From the source code of NSURLSession I found out that it has two initializers:
public /*not inherited*/ init(configuration: NSURLSessionConfiguration)
public /*not inherited*/ init(configuration: NSURLSessionConfiguration, delegate: NSURLSessionDelegate?, delegateQueue queue: NSOperationQueue?)
I expected the "longest" init to be the designated initializer but it's not.
I suspect that that designated initializer is the init()
that is not even specified in the source code.
How can I override the initializer and set up the configuration NSURLSessionConfiguration
?
回答1:
You can not.
The only designated initializer is NSURLSession.init()
and you must call it from your subclass initializer. NSURLSession
configuration
, delegate
and delegateQueue
properties are read-only so you can not manually set them.
The better way is to wrap NSURLSession
with custom class:
class NSURLAuthSession {
private let urlSession: NSURLSession
init(urlSession: NSURLSession) {
self.urlSession = urlSession
}
}
thus you will have more control and customization options.
回答2:
The reason behind that only "dummy" initializer is exposed is that the developers of UIKit don't want you to subclass NSURLSession. If you just want to provide your own URL, write a convenience method on NSURLSession or just configure it yourself using the existing API.
来源:https://stackoverflow.com/questions/32950213/initializer-does-not-override-a-designated-initializer-while-subclassing-nsurlse