什么是Swift中performSelector的替代品?请在下面建议我的代码。我需要更新我在DFURLPrepare类方法中注释的语句。
class Login {
func loginRequest(url:String, dictParams: Dictionary <String, String>)
{
let urlPrepare = DFURLPrepare()
urlPrepare.sendRequest(self, url: url, dictParams: dictParams, successMethod: "getDefaultItemsResponse", errorMethod: nil)
}
}
class DFURLPrepare {
func sendRequest (delegate:AnyObject, url : String, dictParams: Dictionary <String, String>,successMethod: String?, errorMethod:String?){
let networkObj = Network()
let requestResource = Resource(url:url,paramdict: dictParams)
networkObj.load(requestResource){ data, response, error in
if let httpResponse = response as? NSHTTPURLResponse {
let statusCode = httpResponse.statusCode
if statusCode == 200 && data != nil{
/// *************Here as in objeactive C **************//
/// [self.delegate performSelector:successMethod withObject:data]];
///// What would be code at place of above statement
}
}
}
}
}
答案 0 :(得分:1)
您可以performSelector(_:withObject:)
使用NSObject
- 后代:
class Login: NSObject { //<-Login needs to be a subclass of `NSObject`.
func loginRequest(url:String, dictParams: Dictionary <String, String>)
{
let urlPrepare = DFURLPrepare()
urlPrepare.sendRequest(self, url: url, dictParams: dictParams, successMethod: #selector(getDefaultItemsResponse), errorMethod: nil)
}
func getDefaultItemsResponse(data: NSData?) {
}
}
class DFURLPrepare {
func sendRequest(delegate: NSObject, url : String, dictParams: Dictionary <String, String>,successMethod: Selector, errorMethod: Selector){
//Type of `delegate` needs to be `NSObject`.
let networkObj = Network()
let requestResource = Resource(url:url,paramdict: dictParams)
networkObj.load(requestResource){ data, response, error in
if let httpResponse = response as? NSHTTPURLResponse {
let statusCode = httpResponse.statusCode
if statusCode == 200 && data != nil{
delegate.performSelector(successMethod, withObject: data)
}
}
}
}
}
但许多Swift程序员使用闭包是一种更优先的方式:
class Login {
func loginRequest(url: String, dictParams: Dictionary <String, String>) {
let urlPrepare = DFURLPrepare()
urlPrepare.sendRequest(url, dictParams: dictParams, successHandler: getDefaultItemsResponse, errorHandler: nil)
}
func getDefaultItemsResponse(data: NSData?) {
}
}
class DFURLPrepare {
func sendRequest(url : String,
dictParams: [String: String],
successHandler: ((NSData?)->Void)?,
errorHandler: ((NSError?)->Void)?
) {
let networkObj = Network()
let requestResource = Resource(url:url,paramdict: dictParams)
networkObj.load(requestResource){ data, response, error in
if let httpResponse = response as? NSHTTPURLResponse {
let statusCode = httpResponse.statusCode
if statusCode == 200 && data != nil{
successHandler?(data)
}
}
}
}
}