gpt4 book ai didi

ios - 使用单独的类在 Swift 中处理 Alamofire 对 TableView 的响应的最佳方法是什么?

转载 作者:行者123 更新时间:2023-11-28 10:21:20 25 4
gpt4 key购买 nike

我正在编写一个类来处理返回 JSON 以填充 TableView 的服务器请求。这是我第一次做这种事情,我很好奇这里使用的最佳范例是什么。委托(delegate)之类的东西比使用 dispatch_async 更好吗? Alamofire 的响应几乎是异步的,所以我无法从中返回数据。由于我的请求发生在一个共享的(它存在于我创建的框架中,因此我可以在多个目标中使用它)ServerManager 类,我需要以某种方式将它发送到 TableView,而且我不确定最好的方法是什么去做。

委派相对于后台线程的优点是什么,反之亦然?我知道这个问题可能在这里被问了很多,但我在搜索时似乎找不到很好的解释。

最佳答案

ServerManager 中的方法应该传递一个闭包( block )。这不需要委托(delegate),也不需要在 View Controller 中进行分派(dispatch)。

class ServerManager {
func fetchObjectsWithOptions(options: [AnyObject], completion: (items: [AnyObject], error: ErrorType?) -> Void) {
// Use the options to setup and make the request
// Be sure it executes on the main thread
completion(items: items, error: nil)
// Any finishing needed
}
}

// ...

class MyTableViewController: UITableViewController {

lazy var serverManager = ServerManager()
var items: [AnyObject] = []

override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)

serverManager.fetchObjectsWithOptions([]) {
items, error in

if error == nil {
self.items = items
self.tableView.reloadData()
}
}
}

}

闭包是可以分配给变量的函数。闭包在 Swift 中相对简单。这是一个不带参数且返回类型为 void 的闭包。

{ () -> Void in print("foo") }

下面,变量x 的类型签名为() -> Void,并被赋值为闭包。执行闭包只需调用一个函数 x()

let x: () -> Void = { () -> Void in print("foo") }
x() // prints foo

闭包可以作为函数参数传递。当调用 funcWithClosure() 时,它会执行闭包。

func funcWithClosure(x: () -> Void) {
x()
}

funcWithClosure({ () -> Void in print("foo") })

带参数的闭包将参数及其类型指定为闭包类型的一部分。

func funcWithClosure2(x: (string: String) -> Void) {
x(string: "foo") // <-- parameters must be named
}

funcWithClosure2({ (string: String) -> Void in print(string) })

类型推断引擎允许您从闭包中移除类型。

funcWithClosure({ print("foo") }) // <-- No type declaration
funcWithClosure2({ string in print(string) }) // <-- Only parameter name

此外,如果闭包是最后一个参数,则不需要将闭包括起来。

funcWithClosure { print("foo") }

最后,这是一个以闭包结尾的多参数示例。

func funcWithString(string: String, closure: (string: String) -> Void) {
closure(string: string)
}

funcWithString("foo", closure: { (string: String) -> Void in print(string) })

或者,您可以使用不太冗长的语法。

funcWithString("foo") { string in print(string) }

关于ios - 使用单独的类在 Swift 中处理 Alamofire 对 TableView 的响应的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34548180/

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