[英]Calling a delegate method in dispatch_async
我已经实现了一个简单的委托模式,我需要在主队列中调用委托方法。 这是执行此调用的代码:
dispatch_async(dispatch_get_main_queue()){
self.delegate?.readerDidCompleteDownload(self, data: tempData)
}
但是由于这个错误我无法编译
Could not find member: readerDidCompleteDownload:
该方法在委托中实现,协议正确定义了该方法
@objc protocol DBDataReaderDelegate{
func readerDidCompleteDownload(reader: DBDataReader, data:String[])
@optional func readerDidFailDownload(reader: DBDataReader)
}
如果我在dispatch_async
之外调用此方法,则它可以正常工作。
我做错了吗?
我在NSURLSessionDownloadDelegate函数中调用此方法...在此报告完整代码,只是为了向此问题添加更多信息:
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didFinishDownloadingToURL location: NSURL!){
let data = NSData(contentsOfURL: location)
var error:NSError
let string = NSString(data: data, encoding: NSUTF8StringEncoding)
if let JSONObj:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? NSDictionary {
var tempData:String[] = String[]()
if let shots = JSONObj["shots"] as? NSDictionary[]{
for (index, element) in enumerate(shots){
if let title:String = element["title"] as? String{
tempData += title
}
}
dispatch_async(dispatch_get_main_queue()){
self.delegate?.readerDidCompleteDownload(self, data: tempData)
}
}
}else{
delegate?.readerDidFailDownload?(self)
}
}
„The type of this function is () -> (), or “a function that has no parameters,
and returns Void.” Functions that don’t specify a return value always
return Void, which is equivalent to an empty tuple in Swift, shown as ().”
Apple Inc. „The Swift Programming Language”. iBooks
因为委托是可选类型并且可以为nil,并且Swift中的每个函数或方法都必须返回值,例如Void !,(),所以只需要在dispatch_async的末尾添加元组()
。
dispatch_async(dispatch_get_main_queue()){
self.delegate?.readerDidCompleteDownload(self, data: tempData)
()
}
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.delegate?.readerDidCompleteDownload(self, data: tempData)
}
如果没有() -> Void in
,则Swift会推断闭包的类型。 推断的结果来自“ 可选链接 ” readerDidCompleteDownload
,所以它是Void?
。 这使得推断的闭包类型() -> Void?
(可选的Void),它与dispatch_block_t
含义不同: () -> Void
(非可选的Void)。
这可以在Swift中使用一些语法糖。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.