如何正确处理带参数的Swift块中的弱自我 [英] How to Correctly handle Weak Self in Swift Blocks with Arguments

查看:123
本文介绍了如何正确处理带参数的Swift块中的弱自我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 TextViewTableViewCell 中,我有一个变量来跟踪块和传入块的配置方法。

这是我的 TextViewTableViewCell 类:

In my TextViewTableViewCell, I have a variable to keep track of a block and a configure method where the block is passed in and assigned.
Here is my TextViewTableViewCell class:

//
//  TextViewTableViewCell.swift
//

import UIKit

class TextViewTableViewCell: UITableViewCell, UITextViewDelegate {

    @IBOutlet var textView : UITextView

    var onTextViewEditClosure : ((text : String) -> Void)?

    func configure(#text: String?, onTextEdit : ((text : String) -> Void)) {
        onTextViewEditClosure = onTextEdit
        textView.delegate = self
        textView.text = text
    }

    // #pragma mark - Text View Delegate

    func textViewDidEndEditing(textView: UITextView!) {
        if onTextViewEditClosure {
            onTextViewEditClosure!(text: textView.text)
        }
    }
}

当我在 cellForRowAtIndexPath 方法中使用configure方法时,如何在我传入的块中正确使用弱自我。< br>
这是我没有弱自我的东西:

When I use the configure method in my cellForRowAtIndexPath method, how do I properly use weak self in the block that I pass in.
Here is what I have without the weak self:

let myCell = tableView.dequeueReusableCellWithIdentifier(textViewCellIdenfitier) as TextViewTableViewCell
myCell.configure(text: body, onTextEdit: {(text: String) in
   // THIS SELF NEEDS TO BE WEAK  
   self.body = text
})
cell = bodyCell

UPDATE :我使用工作了以下... [弱自我]

let myCell = tableView.dequeueReusableCellWithIdentifier(textViewCellIdenfitier) as TextViewTableViewCell
myCell.configure(text: body, onTextEdit: {[weak self] (text: String) in
        if let strongSelf = self {
             strongSelf.body = text
        }
})
cell = myCell

当我做 [unowned self] 而不是 [弱自我] 并取出 if 语句,应用程序崩溃。关于如何使用 [无主自我] 的任何想法?

When I do [unowned self] instead of [weak self] and take out the if statement, the app crashes. Any ideas on how this should work with [unowned self]?

推荐答案

如果自我在闭包中可能为零,请使用 [弱自我]

If self could be nil in the closure use [weak self].

如果永远不会在关闭时使用 [无主自我]

If self will never be nil in the closure use [unowned self].

如果使用 [无主自我]时崩溃] 我猜在封闭的某个时刻自我是零,这就是为什么你必须选择 [弱自我]

If it's crashing when you use [unowned self] I would guess that self is nil at some point in that closure, which is why you had to go with [weak self] instead.

我真的很喜欢手册中有关使用无主<的所有部分/ strong>在闭包中:

I really liked the whole section from the manual on using strong, weak, and unowned in closures:

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html

注意:我使用了术语闭合而不是阻止这是更新的Swift术语:

Note: I used the term closure instead of block which is the newer Swift term:

块之间的差异(目标C)在ios中关闭(Swift)

这篇关于如何正确处理带参数的Swift块中的弱自我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆