[英]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.