我们如何声明一个全局的(私有实例变量)以接受其中的块。我们需要合成它吗?与此相关的内存管理问题是什么。
我从第三方方法中收到了一个块,我想将其保存在实例变量中并在以后使用它。
我从第三方方法中收到了一个块,我想将其保存在实例变量中并在以后使用它。
这里是一个没有使用ARC的例子,演示了在后台进行一些工作后将块存储为完成回调的方式:
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
Blocks编程主题
:
You can copy and release blocks using C functions:
Block_copy(); Block_release();
If you are using Objective-C, you can send a block
copy
,retain
, andrelease
(andautorelease
) messages.To avoid a memory leak, you must always balance a
Block_copy()
withBlock_release()
. You must balancecopy
orretain
withrelease
(orautorelease
)—unless in a garbage-collected environment.
retain
、release
或autorelease
。 - Abizern