我有OutputStream
的子类。我有两个init()
方法,其中一个前缀为convenience
。
这是我的代码:
class FileOutputStream : OutputStream
{
fileprivate let filepath:URL
fileprivate let channel:DispatchIO!
convenience init?(filename:String) {
let pathURL = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in:.userDomainMask).first!.appendingPathComponent(filename)
self.init(filepath:pathURL)
}
init?(filepath f:URL) {
self.filepath = f
//if let path = f.path,
if let cpath = (f.path).cString(using: String.Encoding.utf8) {
let outputflag:Int32 = O_CREAT | O_WRONLY // create, write-only
let mode:mode_t = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH // permissions: u+rw, g+r, o+r
self.channel = DispatchIO(type: DispatchIO.StreamType.stream, path:cpath, oflag:outputflag,mode: mode, queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.background)) { (errcode:Int32) -> Void in
if errcode != 0 {
print("FileOutputStream: error creating io channel")
}
}
}
else {
self.channel = nil
return nil
}
}
func write(_ string: String) {
if let dataString = string.data(using: String.Encoding.utf8) {
dataString.withUnsafeBytes {(bytes: UnsafePointer<UInt8>) -> Void in
var data = DispatchData.empty
data.append(bytes, count: dataString.count)
self.channel.write(offset: 0, data: data, queue: DispatchQueue.global(qos:.background), ioHandler: { (complete: Bool, data: DispatchData?, errorCode: Int32) in
//handle progress reporting here
if errorCode != 0 {
print("FileOutputStream: error writing data to channel")
}
})
}
}
}
deinit {
self.channel.close(flags: DispatchIO.CloseFlags.stop)
}
}
我收到错误
在super.init调用之前'self'使用
我试过写
super.init()
但仍然有错误。如果有人知道,请帮助我。
答案 0 :(得分:2)
在super.init(url: f, append: false/true)
方法的末尾使用init?(filepath f:URL)
。
您的初始化程序必须调用超类的指定初始化程序。调用OutputStream
类中可用的任何这些初始化方法...
public init(toMemory: ())
public init(toBuffer buffer: UnsafeMutablePointer<UInt8>, capacity: Int)
@available(iOS 4.0, *)
public init?(url: URL, append shouldAppend: Bool)