典型的答案是将您的类创建为NSOperation
子类并为其提供自定义完成块。如果您的目标是更新完成块中的 UI 或某些模型对象,请确保将该块分派回主队列:
// CustomOperation.h
#import <Foundation/Foundation.h>
typedef void(^CustomOperationCompletion)(NSString *string);
@interface CustomOperation : NSOperation
@property (nonatomic, copy) CustomOperationCompletion customOperationCompletion;
- (id)initWithCustomCompletion:(CustomOperationCompletion)completion;
@end
和
// CustomOperation.m
#import "CustomOperation.h"
@implementation CustomOperation
- (id)initWithCustomCompletion:(CustomOperationCompletion)completion {
self = [super init];
if (self) {
self.customOperationCompletion = completion;
}
return self;
}
- (void)main {
NSLog(@"%s starting", __FUNCTION__);
sleep(5);
NSString *string = [[NSDate date] description];
if (self.customOperationCompletion) {
[[NSOperationQueue mainQueue] addOperationWithBlock: ^{
self.customOperationCompletion(string);
}];
}
NSLog(@"%s ending", __FUNCTION__);
}
@end
然后你可以用类似的东西来调用它:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
CustomOperation *operation = [[CustomOperation alloc] initWithCustomCompletion:^(NSString *string) {
// update the UI with the results of the operation; here I'm just going to log it
NSLog(@"all done, string=%@", string);
}];
[queue addOperation:operation];
显然,更改您的CustomOperationCompletion
参数以包含您想要返回的任何内容(我只是传回一个字符串)。