使用Xcode LLDB控制台调试Swift中的闭包

m3r*_*3rk 14 closures memory-leaks ios lldb swift

我坚持使用Xcode LLDB调试控制台的有趣行为.当我使用weak self + guard self语句来防止内存泄漏时,我在尝试打印闭包参数(如示例中的响应)或者闭包中的任何class/struct属性时调试代码时会遇到奇怪的行为.这是一个闭包的例子和print语句的行有一个断点,我试图从Xcode控制台打印响应参数.

Alamofire.request(url).responseJSON { [weak self] response in
    guard let self = self else { return }
    print("This line has a breakpoint and I am trying to print response from debug console")
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用这样的命令:

po response
p response
print response
e response
expression response
Run Code Online (Sandbox Code Playgroud)

总是我得到这样的错误:

    (lldb) po response
error: warning: <EXPR>:12:9: warning: initialization of variable '$__lldb_error_result' was never used; consider replacing with assignment to '_' or removing it
    var $__lldb_error_result = __lldb_tmp_error
    ~~~~^~~~~~~~~~~~~~~~~~~~
    _

error: <EXPR>:18:5: error: value of type 'APIManager' has no member '$__lldb_wrapped_expr_25'
    $__lldb_injected_self.$__lldb_wrapped_expr_25(     
    ^~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

你也坚持过这个问题吗?为什么我会得到该错误以及除了删除weak self + guard self语句或插入print(response)闭包代码之外可能的解决方法?

临时解决方案:

不要使用自阴影,而是使用类似这样的变量名称,_self然后你不会像上面那样得到lldb错误:

Alamofire.request(url).responseJSON { [weak self] response in
    guard let _self = self else { return }
    // your code here ...
}
Run Code Online (Sandbox Code Playgroud)

Cla*_*ges 1

尽管您可能早已忘记了这个问题,但我的第一个猜测是这是编译器优化,因为您没有response在闭包中的任何地方使用该参数。

@matt 在评论中对此有更多了解。

  • 不,那不再正确了。即使在调试版本中,未使用的值也不在异步闭包中的 LLDB 范围内。 (2认同)