我建议使用块或闭包回调,而不是使用NSThread和选择器。
例如,在我的API中,我有一个follow方法:
Swift:
下面是更新后的实现。
func getUsers(completion: (result: NSArray?, error: NSError?)->())
{
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
if error != nil {
completion(nil, error)
} else {
var result:NSArray = data to NSArray;
completion(result, nil)
}
}
task.resume()
}
Objective-C:
...
typedef void (^CBSuccessBlock)(id result);
typedef void (^CBFailureBlock)(NSError *error);
...
- (void)usersWithSucces:(CBSuccessBlock)success failure:(CBFailureBlock)failure
{
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:url]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSArray *users =
if(error)
failure(error);
else
success(users);
}] resume];
}
然后,只需要从视图控制器中调用API:
Objc:
[api usersWithSucces:^(id result)
{
} failure:^(NSError *error)
{
}];
Swift:
api.getUsers({(result: AnyObject?, error: NSError?) -> Int in
})
更新:
与此同时,我发现这个问题和答案仍然有用并且令人感兴趣。下面是使用泛型枚举作为结果对象的Swift实现的更新版本:
enum AsyncResult<T>
{
case Success(T)
case Failure(NSError?)
}
class CustomUserObject
{
}
func getUsers(completion: (AsyncResult<[CustomUserObject]>)->())
{
let request = NSURLRequest()
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
if let error = error
{
completion(AsyncResult.Failure(error))
} else {
let result: [CustomUserObject] = []
completion(AsyncResult.Success(result))
}
}
task.resume()
}
getUsers { (result) in
switch result
{
case .Success(let users):
break
case .Failure(let error):
break
}
}
((void (*)(id, SEL))objc_msgSend)(callbackViewController, selector);
或者只是[callbackViewController performSelector:selector];
。 - newacctviewController.performSelector(onMainThread: selector, with: nil, waitUntilDone: false)
- Noor