ios - 在 dispatch_async 中调用委托(delegate)方法

标签 ios cocoa-touch swift

我已经实现了一个简单的委托(delegate)模式,我需要在主队列中调用委托(delegate)方法。这是执行此调用的代码:

dispatch_async(dispatch_get_main_queue()){
    self.delegate?.readerDidCompleteDownload(self, data: tempData)
} 

但是因为这个错误我无法编译

Could not find member: readerDidCompleteDownload:

该方法在委托(delegate)中实现并且协议(protocol)正确定义了它

@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

因为delegate是可选类型,可以为nil,而Swift中的每一个函数或方法都必须有返回值,例如Void!,(),所以只需要在末尾加上元组() dispatch_async 的

dispatch_async(dispatch_get_main_queue()){
    self.delegate?.readerDidCompleteDownload(self, data: tempData)
    ()
}

关于ios - 在 dispatch_async 中调用委托(delegate)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24402714/

相关文章:

iOS 检测 : how to interpret Memory Allocations Template?

ios 共享扩展帖子按钮标题

ios - 在谷歌地图中设置多个标记

ios - UISplitView 导航栏后面奇怪的背景

iphone - 为 iPhone 制作 map 应用程序的最佳方式是什么

ios - UIView 无法识别 subview

iphone - 为 UITableView 设置三边边框 - IOS

ios - 如何将颜色输入到我不是以编程方式创建的 plist 中?

ios - 如果在数字之前按下计算器应用程序中的运算符(operator)按钮,则应用程序崩溃

ios - 如何使水平 StackView 具有第一个元素的宽度并填充其余元素