// Capture a strong reference to someView, to make sure it's still around later on.
__block UIView *v = someView;
//Need to go back to the main thread since this is UI related
dispatch_async(dispatch_get_main_queue(), ^{
[v addSubview:self]
// Release v (assuming ARC). If nothing else has retained someView, this means
// that someView will be deallocated - but we're on the main thread,
// so that's fine. What we don't want is a background dealloc.
v = nil;
});
OR
// Capture a strong reference to someView, to make sure it's still around later on.
__weak UIView *weakRef = someView;
//Need to go back to the main thread since this is UI related
dispatch_async(dispatch_get_main_queue(), ^{
// This is thread-safe because someView should only be de-alloced on the main thread.
// consequently our access to weakRef is safe.
UIView *strongRef = weakRef;
[strongRef addSubview:self];
});
什么不可以做的就是这个。
UIView *strongRef = whatever;
dispatch_async(downloadQueue, ^{
dispatch_async(dispatch_get_main_queue(), ^{
[someView addSubview:self]
});
// If, by the time we get here, the dispatch to the main queue has already run,
// then we will send a release to someView on a background thread. If it's the last
// remaining reference - and it might be, unlikely as it is, then we just dealloced
// a UIView in the background. This is bad.
});
如果你使用ARC并且'someView'被声明为'weak'引用,那么如果对象被释放,它将是'nil'。这将避免保持对不再存在的视图的引用的问题。 – rmaddy 2013-04-30 16:19:38
这是正确的。我将该属性定义为“分配”而不是弱。改变为弱解决了这个问题。 – soleil 2013-04-30 16:33:58
在ARC中使用“assign”有效地消除了ARC的所有优势! :) – matt 2013-04-30 17:08:11