A C function pointer cannot be formed from a closure that captures context
是否有解决方法或是否仍然可以更改闭包内的变量?
我的代码:
let callback: @convention(c) (readStream: CFWriteStream!,event: CFStreamEventType,data: UnsafeMutablePointer<VoID>) -> VoID = { (readStream,event,data) -> VoID in switch event { case CFStreamEventType.ErrorOccurred: self.isError = true break case CFStreamEventType.EndEncountered: self.isRunLoop = false break case CFStreamEventType.HasBytesAvailable: break case CFStreamEventType.OpenCompleted: break case CFStreamEventType.CanAcceptBytes: self.bytesWritten = CFWriteStreamWrite(readStream,self.buffer,self.leftOverSize) break default: break }}let registeredEvents: CFOptionFlags = CFStreamEventType.CanAcceptBytes.rawValue | CFStreamEventType.HasBytesAvailable.rawValue | CFStreamEventType.ErrorOccurred.rawValue | CFStreamEventType.EndEncountered.rawValue | CFStreamEventType.None.rawValuevar context = CFStreamClIEntContext(version: CFIndex(0),info: nil,retain: nil,release: nil,copyDescription: nil)let stream = CFWriteStreamCreateWithFTPURL(nil,uploadURL).takeUnretainedValue()CFWriteStreamSetClIEnt(stream,registeredEvents,callback,&context)解决方法 我假设你想使用这个回调将它作为第三个参数(clIEntCB)传递给 CFWriteStreamSetClient.
由于该参数具有以下类型定义
typedef voID (*CFWriteStreamClIEntCallBack) ( CFWriteStreamRef stream,CFStreamEventType eventType,voID *clIEntCallBackInfo );
您只能使用全局函数或不从周围上下文捕获任何变量(如self)的闭包.
在这种情况下你可以做的是将self传递给CFStreamClIEntContext结构的info字段(CFWriteStreamSetClIEnt的第4个参数),并使用该信息在闭包内重构self:
let callback: @convention(c) (readStream: CFWriteStream!,data) -> VoID in // assuming your class name is ClIEnt let clIEnt = unsafeBitCast(data.memory,ClIEnt.self) switch event { case CFStreamEventType.ErrorOccurred: clIEnt.isError = true case CFStreamEventType.EndEncountered: clIEnt.isRunLoop = false case CFStreamEventType.HasBytesAvailable: break case CFStreamEventType.OpenCompleted: break case CFStreamEventType.CanAcceptBytes: clIEnt.bytesWritten = CFWriteStreamWrite(readStream,clIEnt.buffer,clIEnt.leftOverSize) default: break }}var context = CFStreamClIEntContext(version: 0,info: unsafeBitCast(self,UnsafeMutablePointer<VoID>.self),copyDescription: nil)CFWriteStreamSetClIEnt(stream,&context)
注意.与Objective-C一样,您需要确保在流之前不会销毁self,否则如果流接收到新事件,您可能会遇到崩溃.
总结以上是内存溢出为你收集整理的关闭捕获上下文Swift全部内容,希望文章能够帮你解决关闭捕获上下文Swift所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)