保存实例变量中的块 [英] Saving a block in instance variable
本文介绍了保存实例变量中的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们如何声明一个全局(私有实例变量)来接受一个块。我们需要合成它,
How do we declare a global(private instance variable) to accept a block in it. Do we need to synthesis it & what are the memory management implications with it.
我有一个从第三方方法接收的块,我想保存在实例变量&
I have a block received from a third party method which I want to save in the instance variable & use it at a later stage.
推荐答案
这里是一个(无ARC)的例子,在完成回调后存储一个块一些工作在后台:
Here's an (ARC-less) example of storing a block for a completion callback after doing some work in the background:
Worker.h:
@interface Worker : NSObject
{
void (^completion)(void);
}
@property(nonatomic,copy) void (^completion)(void);
- (void)workInBackground;
@end
Worker.m:
@implementation Worker
@synthesize completion;
- (void)dealloc
{
Block_release(completion);
[super dealloc];
}
- (void)setCompletion:(void (^)(void))block
{
if ( completion != NULL )
Block_release(completion);
completion = Block_copy(block);
}
- (void)workInBackground
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)
{
// Do work..
dispatch_async(dispatch_get_main_queue(), completion);
});
}
@end
这篇关于保存实例变量中的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文