我有以下虚拟架构:一个单例类将接收一些数据,并且在某个时刻(当调用 returnCallback 函数时)将使用回调返回数据。
@interface Helper: NSObject
{
void (^_completionHandler)(int someParameter);
}
+(Helper *)getInstance;
- (void) doSomethingWithCompletionHandler:(void(^)(int))handler;
@end
@implementation Helper
+(Helper *)getInstance {
static Helper *instance = nil;
@synchronized(self) {
if (instance == nil)
instance = [[self alloc] init];
}
return instance;
}
- (void) doSomethingWithCompletionHandler:(void(^)(int))handler
{
//do things
_completionHandler = [handler copy];
//do things
}
-(void) returnCallback
{
int result;
//do things with result
_completionHandler(result);
//nothing to follow, it just returned the result.
}
@end
到目前为止,我只调用过一次助手,一切正常。 例如
[[Helper getInstance] doSomethingWithCompletionHandler:^(int result){
NSLog(@"I received %d", result);
}];
但是现在我需要调用助手两次,第二次在第一个内部。 例如
[[Helper getInstance] doSomethingWithCompletionHandler:^(int result){
[[Helper getInstance] doSomethingWithCompletionHandler:^(int result){
NSLog(@" Yay, I'm good %d", result);
}];
NSLog(@"They stopped retaining me:( %d", result);
}];
问题是(如日志中所示)第一个函数回调从内存中释放,我无法访问结果变量。解决这个问题的一种方法是保留回调的 2 个变量(一个是当前变量,一个是旧变量),但是如果我需要第三个变量怎么办?我尝试使用 block 引用构建 NSMutableArray。但我也必须删除它们,而且我不知道如何删除它们。(它们在 Helper 类中复制,所以我没有对“Testing”类中复制的对象的引用,是吗?)
上面的代码没有经过测试,因为这更多的是一个基于架构的问题。不过,如果有任何错误,我会对其进行测试并尽快编辑消息。
最佳答案
由于您的设计方式,您只能进行一项事件操作。如果您尝试一次执行多个操作,则会发生意外的情况(如您的示例所示)。
有一个既定的模式可以完成这样的事情 - 看看 NSOperation
和 NSOperationQueue
,例如here
关于objective-c - Objective C - 单独释放 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30326229/