初始化器在继承 NSURLSession Swift 时不会覆盖指定的初始化器 [英] Initializer does not override a designated initializer while subclassing NSURLSession Swift
问题描述
我想继承 NSURLSession 类,但我在初始化时遇到问题.基本上我覆盖构造函数并在那里初始化常量 authUrl
然后调用父 init 方法.
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)
}
}
从 NSURLSession 的源代码中我发现它有两个初始化器:
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?)
我希望最长的"init 是指定的初始化程序,但事实并非如此.我怀疑指定的初始化程序是在源代码中甚至没有指定的 init()
.如何覆盖初始化程序并设置配置 NSURLSessionConfiguration
?
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
?
推荐答案
你不能.
唯一指定的初始值设定项是 NSURLSession.init()
并且您必须从您的子类初始值设定项中调用它.NSURLSession
configuration
、delegate
和 delegateQueue
属性是只读的,所以你不能手动设置它们.
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.
更好的方法是用自定义类包装 NSURLSession
:
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.
这篇关于初始化器在继承 NSURLSession Swift 时不会覆盖指定的初始化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!