Ben*_*ynn 5 objective-c ios objective-c-blocks
假设我有一个类(非ARC环境):
@interface SomeObject : NSObject {
UILabel *someLabel;
dispatch_queue_t queue;
}
- (void)doAsyncStuff;
- (void)doAnimation;
@end
@implementation SomeObject
- (id)init {
self = [super init];
if (self) {
someLabel = [[UILabel alloc] init];
someLabel.text = @"Just inited";
queue = dispatch_queue_create("com.me.myqueue", DISPATCH_QUEUE_SERIAL);
}
return self;
}
- (void)doAsyncStuff {
dispatch_async(queue, ^{
...
// Do some stuff on the current thread, might take a while
...
dispatch_async(dispatch_get_main_queue(), ^{
someLabel.text = [text stringByAppendingString:@" in block"];
[self doAnimation];
}
}
}
- (void)doAnimation {
...
// Does some animation in the UI
...
}
- (void)dealloc {
if (queue) {
dispatch_release(queue);
}
[someLabel release];
[super dealloc];
}
Run Code Online (Sandbox Code Playgroud)
如果我的块被启动,然后其他所有持有对该对象实例的引用的东西都会释放它,我保证不会调用dealloc,因为嵌套块引用了一个实例变量(和自己) - dealloc嵌套块退出后会发生什么?我的理解是我的街区有很强的自我参考,所以这应该是犹太人.
出于您所说的原因,这很好。
需要注意的重要一点是,如果类(由 表示self)以任何方式保留该块,您将创建一个保留周期。因为您正在内联定义它并将其传递给dispatch_async,所以应该没问题。