【发布时间】:2014-08-19 12:55:21
【问题描述】:
在我的TextViewTableViewCell 中,我有一个变量来跟踪一个块和一个用于传递和分配块的配置方法。
这是我的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)
}
}
}
当我在cellForRowAtIndexPath方法中使用configure方法时,如何在我传入的块中正确使用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
更新:我得到以下使用[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] 一起工作的任何想法?
【问题讨论】:
-
那您能选择下面的答案作为正确答案吗?另请注意,使用 unowned 你不需要在你的闭包中加强 self 。 Unowned在这里总比weak好,因为你的单元格和视图控制器的生命周期是相互关联的。
-
我意识到 [unowned self] 是更好的选择,但是当我使用它时我的应用程序崩溃了。希望看到使用它来结束答案的代码示例。
-
来自文档:“与弱引用一样,无主引用不会对其所引用的实例保持强控制。然而,与弱引用不同的是,无主引用被假定始终具有值. " 如果您的应用程序崩溃,很可能是因为 unowned 在运行时被应用于一个为零的值。
-
可能比 if let 绑定到 strongSelf 更好。只是说,这就像完美的候选人:-D
-
@NatashaTheRobot,[weak self] 是什么语法?看起来像是在目标 C 中传递的消息。请您在问题中添加更多关于语法的信息。
标签: ios swift retain-cycle