使用 Singleton 来表示“API Manager”对象是一种典型的设计模式,如下所示:-
class APIManager {
let ENDPOINT_URL = "http://remote-server-fqdn.com"
var storage : Storage!
var currentlyLoggedIn = false
class var sharedInstance: APIManager {
struct Static {
//---to contain the one and only instance of this class---
static var instance: APIManager!
//---a token to ensure that the class is only instantiated once---
static var token: dispatch_once_t = 0
}
//---executes a block object once and only once for the lifetime of an application---
dispatch_once(&Static.token) {
//---creates an instance of this class---
Static.instance = APIManager()
Static.instance.storage = Storage.sharedInstance
}
//---returns the instance of this class---
return Static.instance
}
这确保了我们拥有一个APIManager
具有一致标记的对象,我们可以在 ViewController 或 Model 方法的不同部分使用它。问题不大,很容易理解。
问题
但是,问题是 --- 如果我在课堂上使用诸如 Alamofire 或 AFNetworking 之APIManager
类的库作为方法,是否还包括本质上已经异步的实际 API 服务器调用(或任何类型的异步执行)?
这些(异步)方法嵌套在我的 Singleton 类中的事实是否会导致任何意外的性能问题或意外的副作用?
我知道async
服务器API调用或dispatch_async
方法将使用GCD并且仍然可以实现并发。
作为一个额外的问题:Singleton 的异步方法是否实现了这种并发性调用并发并行或并发但不并行?
例如,像这样:-
class APIManager {
// .... same block of code as above for declaring dispatch_once above.
// additional code which are API server calls (and async by nature) here
func loginRequest(username : String, password : String, completion: (loginSuccess : Bool) -> Void) {
// Alamofire.request ...
}
func getRequest(...) {
// Alamofire.request ...
}
func postRequest(...) {
// Alamofire.request ...
}
func testAsync() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
println("just do something asynchronously")
}
}
}