- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
最近在关注 Apple 文档之后
我使用以下约定来避免保留周期问题。
__weak __typeof(self) weak_self = self;
void(^completionBlock)(void) = ^(){
__typeof(self) strong_self = weak_self;
if (strong_self) {
if (strong_self->_completion != NULL) {
strong_self->_completion();
}
}
};
但是发现这段代码崩溃了,因为 self 在调用 block 之前被释放了。
当我使用以下内容时发现它正在工作。
__block __typeof(self) block_self = self;
void(^completionBlock)(void) = ^(){
if (block_self->_completion != NULL) {
block_self->_completion();
}
};
现在我很困惑什么时候应该使用 __weak 引用。仅在下面的“self.completionBlock”
情况下__weak __typeof(self) weak_self = self;
self.completionBlock = ^(){
if (weak_self->_completion != NULL) {
weak_self->_completion();
}
};
有关此条件的任何说明对我都非常有用。
我的实现代码如下。
============================================= ==
@implementation MyViewController
//starting point
- (void)myPushMethod {
__weak __typeof(self) weak_self = self;
MyViewControllerTransitioning *delegateObj = [[MyViewControllerTransitioning alloc] initWithCompletion:^{
//resetting the delegate
__typeof(self) strong_self = weak_self;
if (strong_self) {
strong_self.navigationController.delegate = nil;
}
}];
self.navigationController.delegate = delegateObj;
[self.navigationController pushViewController:someViewController animated:_animated];
//it is found that delegateObj is getting deallocated while reaches this point
}
@end
============================================= ==
@implementation MyViewControllerTransitioning
- (instancetype)initWithCompletion:(completionHandler)completionHandler
{
if(self = [super init])
{
if (completionHandler != NULL) {
_completion = completionHandler;
}
}
return self;
}
- (id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
animationControllerForOperation:(UINavigationControllerOperation)operation
fromViewController:(UIViewController *)fromVC
toViewController:(UIViewController *)toVC
{
id<UIViewControllerAnimatedTransitioning> animationTransitioning = nil;
//crashes here
__block __typeof(self) block_self = self;
void(^completionBlock)(void) = ^(){
if (block_self->_completion != NULL) {
block_self->_completion();
}
};
//showing presentation-up animation if Push
if (operation == UINavigationControllerOperationPush) {
animationTransitioning = [[MyAnimator alloc] initWithAnimationCompletion:completionBlock];
}
return animationTransitioning;
}
- (void)dealloc{
//dealloc is called before invoking completionBlock
}
@end
============================================= ==
@implementation MyAnimator
- (instancetype)initWithAnimationCompletion:(presentationUpCompletion)completionHandler
{
if(self = [super init])
{
if (completionHandler != NULL) {
_completion = completionHandler;
}
}
return self;
}
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
{
return my_duration;
}
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
//animation logic
[UIView animateWithDuration:duration animations: ^{
//animation logic
} completion: ^(BOOL finished) {
[transitionContext completeTransition:![transitionContext transitionWasCancelled]];
}];
}
- (void)animationEnded:(BOOL) transitionCompleted {
if (transitionCompleted && _completion != NULL) {
_completion();
}
}
@end
最佳答案
在下面的原始回答中,我介绍了标准的 weakSelf
模式(以及 weakSelf
-strongSelf
“舞蹈”)。我的结论是,您引用的演示幻灯片关于 weakSelf
模式是绝对正确的(尽管该演示文稿在风格上已经过时)。
您随后提供了一个更完整的代码示例,结果发现它遇到了一个不同的、不相关的问题。 (更糟糕的是,这个问题只有在解决了强引用循环时才会出现。大声笑。)最重要的是,代码将导航 Controller 的委托(delegate)设置为超出范围的本地对象。因为导航 Controller 不保留它的委托(delegate),所以您最终会得到一个指向这个已释放对象的悬空指针。
如果您保留自己对此委托(delegate)对象的 strong
引用(防止它被释放),问题就会消失。
我的原始答案如下。
你说:
used the following conventions to avoid retain cycle issues.
__weak __typeof(self) weak_self = self;
void(^completionBlock)(void) = ^(){
__typeof(self) strong_self = weak_self;
if (strong_self) {
if (strong_self->_completion != NULL) {
strong_self->_completion();
}
}
};But this code is found to be crashing because self is getting deallocated before invoking the block.
不,这是一种很常见的模式(常被戏称为“弱我强我舞”)。这没有错。如果它崩溃了,那是因为其他原因。
当然,我会使用现代命名约定(weakSelf
和 strongSelf
而不是 weak_self
和 strong_self
) .我会删除 __typeof
开头的 __
。而且我不会倾向于取消引用和 ivar,而是使用属性。所以,我可能会得到类似这样的结果:
__weak typeof(self) weakSelf = self;
void(^completionBlock)(void) = ^(){
typeof(self) strongSelf = weakSelf;
if (strongSelf) {
if (strongSelf.completion != NULL) {
strongSelf.completion();
}
}
};
但是,如果它崩溃了,那么您还有其他问题。坦率地说,您有一个调用 block 的 block ,因此很难猜测您的问题出在哪里,但问题不在于“弱 self ”模式。
稍后您继续建议使用:
__block __typeof(self) block_self = self;
这并不像您认为的那样。 “weak self”模式的目标是打破强引用循环(以前称为 retain cycle),但是在 ARC 中,这个 __block
引用没有解决那个强引用循环。请注意,在非 ARC 代码中,此 block_self
模式用于中断保留循环,但它不会在 ARC 中完成这项工作。
最后,你继续建议:
__weak __typeof(self) weak_self = self;
self.completionBlock = ^(){
if (weak_self->_completion != NULL) {
weak_self->_completion();
}
};
这有两个严重的问题。首先,您正在取消引用一个弱变量。如果 weak_self
是 nil
,它就会崩溃。其次,即使您通过使用属性访问器方法而不是取消引用 ivars 来解决这个问题,您也会遇到另一个问题,即竞争条件。
最重要的是,该演示文稿中的“弱 self ”模式是正确的。同样,您第一个例子中的“弱 self , strong self 舞蹈”也是正确的。如果它为您崩溃,您必须向我们提供 MCVE这重现了问题。但在 ARC 代码中,这是一个完全有效的模式。
关于ios - self.completionBlock = ^{} 和 (void)(^completionBlock)(void) = ^{} 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29488965/
让我们写一个简单的类在我的脑海中解释: class SomeClass { var happyToUsed = 10 } 并创建一个对象 let someObject = SomeClass(
采用 self 的方法与采用 &self 甚至 &mut self 的方法有什么区别? 例如 impl SomeStruct { fn example1(self) { } fn ex
请观察以下代码(Win10上的python 3.6,PyCharm),函数thread0(self)作为线程成功启动,但是 thread1(self)似乎与thread0(self)不同已设置。 se
backbone.js 开始于: //Establish the root object, `window` (`self`) in the browser, or `global` on the s
做的事: self = self.init; return self; 在 Objective-C 中具有相同的效果: self.init() 快速? 例如,在这种情况下: else if([form
我查看了关于堆栈溢出的一些关于使用[weak self]和[unowned self]的问题的评论。我需要确保我理解正确。 我正在使用最新的 Xcode - Xcode 13.4,最新的 macOS
我面临在以下模型类代码中的 self.init 调用或分配给 self 之前使用 self 的错误tableview单元格项目,它发生在我尝试获取表格单元格项目的文档ID之后。 应该做什么?请推荐。
晚上好。 我对在 Swift 中转义(异步)闭包有疑问,我想知道哪种方法是解决它的最佳方法。 有一个示例函数。 func exampleFunction() { functionWithEsca
我需要在内心深处保持坚强的自我。 我知道声明[weak self]就够了外封闭仅一次。 但是guard let self = self else { return }呢? ,是否也足以为外部闭包声明一
代码 use std::{ fs::self, io::self, }; fn rmdir(path: impl AsRef) -> io::Result { fs::remo
我检查了共享相同主题的问题,但没有一个解决我遇到的这种奇怪行为: 说我有一个简单的老学校struct : struct Person { var name: String var age:
我应该解释为什么我的问题不是重复的:TypeError: can only concatenate list (not “str”) to list ...所以它不是重复的,因为该帖子处理代码中出现的
我有一个 trait,它接受一个类型参数,我想说实现这个 trait 的对象也会符合这个类型参数(使用泛型,为了 Java 的兼容性) 以下代码: trait HandleOwner[SELF
这个问题在这里已经有了答案: Why would a JavaScript variable start with a dollar sign? [duplicate] (16 个答案) 关闭 8
我总是找到一些类似的代码newPromise.promiseDispatch.apply(newPromise, message),我不明白为什么不使用newPromise.promiseDispat
我看到类似的模式 def __init__(self, x, y, z): ... self.x = x self.y = y self.z = z ... 非
mysql查询示例: SELECT a1.* FROM agreement a1 LEFT JOIN agreement a2 on a1.agreementType = a2.agreementTy
self.delegate = self; 这样做有什么问题吗?正确的做法是什么? 谢谢,尼尔。 代码: (UITextField*)initWith:(id)sender:(float)X:(flo
为什么要声明self在类中需要的结构中不需要?我不知道是否还有其他例子说明了这种情况,但在转义闭包的情况下,确实如此。如果闭包是非可选的(因此是非转义的),则不需要声明 self在两者中的任何一个。
这个问题已经有答案了: What does the ampersand (&) before `self` mean in Rust? (1 个回答) 已关闭去年。 我不清楚 self 之间有什么区别
我是一名优秀的程序员,十分优秀!