gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:34:47 26 4
gpt4 key购买 nike

我已经实现了一个简单的委托(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com