私の にはTextViewTableViewCell
、ブロックを追跡するための変数と、ブロックが渡されて割り当てられる configure メソッドがあります。
これが私のTextViewTableViewCell
クラスです:
//
// 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)
}
}
}
メソッド内で configure メソッドを使用する場合cellForRowAtIndexPath
、渡すブロック内で弱い self を適切に使用するにはどうすればよいでしょうか。
以下は弱い 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
アップデート: 以下を使用して動作させました[weak self]
:
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]
の代わりにを実行し[weak self]
、ステートメントを削除するとif
、アプリがクラッシュします。 でこれをどのように動作させるべきかについて何かアイデアはありますか[unowned self]
?
ベストアンサー1
もし自己クロージャの使用ではnilになる可能性がある【弱い自分】。
もし自己クロージャの使用では決してnilにならない[所有されていない自分]。
使用中にクラッシュする場合は[所有されていない自分]私は、その閉包のどこかの時点でselfがnilになっていると推測します。それが、【弱い自分】その代わり。
マニュアルの使用に関するセクション全体がとても気に入りました強い、弱い、 そして所有されていないクロージャ内:
注: 私は閉鎖の代わりにブロックこれは新しい Swift 用語です: