- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有以下代码(编辑:更新代码以便每个人都可以编译并查看):
import UIKit
struct Action
{
let text: String
let handler: (() -> Void)?
}
class AlertView : UIView
{
init(actions: [Action]) {
super.init(frame: .zero)
for action in actions {
// let actionButton = ActionButton(type: .custom)
// actionButton.title = action.title
// actionButton.handler = action.handler
// addSubview(actionButton)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class TextAlertView : AlertView
{
init() {
super.init(actions: [
Action(text: "No", handler: nil),
Action(text: "Yes", handler: { [weak self] in
//use self in here..
})
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class MyViewController : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let alert = TextAlertView()
view.addSubview(alert)
self.view = view
}
}
每次我实例化 TextAlertView
时,它都会因访问错误而在 super.init
上崩溃。但是,如果我改变:
Action(title: "Yes", { [weak self] in
//use self in here..
})
到:
Action(title: "Yes", {
//Blank.. doesn't reference `self` in any way (weak, unowned, etc)
})
它有效!
有没有一种方法可以在 super 初始化期间引用 self
,无论它是弱还是不在操作 block 内(在上面我在 super.init
的参数中这样做>?
代码编译..它只是在运行时随机崩溃。
最佳答案
简答:
在 super.init
返回之前,您不能捕获并使用 self
作为值。在您的情况下,您正试图“通过” self
到 super.init
作为参数。
至于为什么第二部分有效,仅仅是因为在其中没有使用self
,它没有捕获self
,因此它没有使用self
作为一个值。
如果你不想在闭包中使用self
,那么你不需要担心strong
/weak
引用在那里,因为那里根本没有对 self
的引用(因为它没有被捕获)。没有保留循环的危险。
关于“使用 self
作为值”的简短旁注 - 您可以在赋值的左侧使用 self
来引用 的属性self
初始化它们时:
let myProperty: String
init(with myProperty: String) {
// this usage of self is allowed
self.myProperty = myProperty
super.init(nibName: nil, bundle: nil)
}
带有引用和内容的更长答案:
根据 documentation :
Safety check 4
An initializer cannot call any instance methods, read the values of any instance properties, or refer to self as a value until after the first phase of initialization is complete.
初始化的第一阶段通过调用super.init
结束,当
来自同一文档:
Phase 1
A designated or convenience initializer is called on a class.
Memory for a new instance of that class is allocated. The memory is not yet initialized.
A designated initializer for that class confirms that all stored properties introduced by that class have a value. The memory for these stored properties is now initialized.
The designated initializer hands off to a superclass initializer to perform the same task for its own stored properties.
This continues up the class inheritance chain until the top of the chain is reached.
Once the top of the chain is reached, and the final class in the chain has ensured that all of its stored properties have a value, the instance’s memory is considered to be fully initialized, and phase 1 is complete.
因此只有在调用 super.init
之后,您才可以使用 self
作为值:
Phase 2
Working back down from the top of the chain, each designated initializer in the chain has the option to customize the instance further. Initializers are now able to access self and can modify its properties, call its instance methods, and so on.
Finally, any convenience initializers in the chain have the option to customize the instance and to work with
self
.
现在,当您尝试将 self
用作闭包捕获列表中的值时,它会崩溃,对此我一点都不感到惊讶。更令我惊讶的是编译器确实允许您这样做 - 现在我猜这是一种未实现错误处理的边缘情况。
第二种情况:
Action(title: "Yes", {
//Blank.. doesn't reference `self` in any way (weak, unowned, etc)
})
您并没有真正捕获self
,这就是它被允许并且有效的原因。但是您无权访问 self
。尝试在其中添加一些使用 self
的代码,编译器会报错:
所以最后,如果你想在闭包中使用self
,你将不得不找到一种方法如何首先调用super.init
,然后才调用将 self
捕获闭包添加到属性中。
关于swift - 在 super.init 中引用自己,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48996228/
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: template pass by value or const reference or…? 以下对于将函数
我用相同的参数列表重载了一个运算符两次。但返回类型不同: T& operator()(par_list){blablabla} const T& operator()(par_list){bla
假设我有实现接口(interface) I 的 Activity A。我的 ViewModel 类 (VM) 持有对实现接口(interface) I 的对象的引用: class A extends
PHP 如何解释 &$this ?为什么允许? 我遇到了以下问题,这看起来像是 PHP 7.1 和 7.2 中的错误。它与 &$this 引用和跨命名空间调用以及 call_user_func_arr
谁能解释一下下面“&”的作用: class TEST { } $abc =& new TEST(); 我知道这是引用。但是有人可以说明我为什么以及什么时候需要这样的东西吗?或者给我指向一个对此有很好解
引用变量是一个别名,也就是说,它是某个已存在变量的另一个名字。一旦把引用初始化为某个变量,就可以使用该引用名称或变量名称来指向变量。 C++ 引用 vs 指针 引用很容易与指针混淆,它们之间有三
目录 引言 背景 结论 引言 我选择写C++中的引用是因为我感觉大多数人误解了引用。而我之所以有这个感受是因为我主持过很多C++的面试,并且我很少
Perl 中的引用是指一个标量类型可以指向变量、数组、哈希表(也叫关联数组)甚至函数,可以应用在程序的任何地方 创建引用 定义变量的时候,在变量名前面加个 \,就得到了这个变量的一个引用 $sc
我编写了一个将从主脚本加载的 Perl 模块。该模块使用在主脚本中定义的子程序(我不是维护者)。 对于主脚本中的一个子例程,需要扩展,但我不想修补主脚本。相反,我想覆盖我的模块中的函数并保存对原始子例
我花了几个小时试图掌握 F# Quotations,但我遇到了一些障碍。我的要求是从可区分的联合类型中取出简单的函数(只是整数、+、-、/、*)并生成一个表达式树,最终将用于生成 C 代码。我知道使用
很多时候,问题(尤其是那些标记为 regex 的问题)询问验证密码的方法。似乎用户通常会寻求密码验证方法,包括确保密码包含特定字符、匹配特定模式和/或遵守最少字符数。这篇文章旨在帮助用户找到合适的密码
我想通过 MIN 函数内的地址(例如,C800)引用包含文本的最后一个单元格。你能帮忙吗? Sub Set_Formula() ' ----------------------------- Dim
使用常规的 for 循环,我可以做类似的事情: for (let i = 0; i < objects.length; i++) { delete objects[i]; } 常规的 for-
在 Cucumber 中,您定义了定义 BDD 语法的步骤;例如,您的测试可能有: When I navigate to step 3 然后你可以定义一个步骤: When /^I navigate t
这是什么UnaryExpression的目的,以及应该怎样使用? 最佳答案 它需要一个 Expression对象并用另一个 Expression 包裹它.例如,如果您有一个用于 lambda 的表达式
给出以下内容 $("#identifier div:first, #idetifier2").fadeOut(300,function() { // I need to reference jus
我不知道我要找的东西的正确术语,但我要找的是一个完整的引用,可以放在双引号之间的语句,比如 *, node()、@* 以及所有列出的 here加上任何其他存在的。 我链接到的答案提供了一些细节,但还
This question's answers are a community effort。编辑现有答案以改善此职位。它当前不接受新的答案或互动。 这是什么? 这是常见问答的集合。这也是一个社区Wi
Closed. This question does not meet Stack Overflow guidelines。它当前不接受答案。 想改善这个问题吗?更新问题,以便将其作为on-topic
考虑下一个代码: fn get_ref(slice: &'a Vec, f: fn(&'a Vec) -> R) -> R where R: 'a, { f(slice) } fn m
我是一名优秀的程序员,十分优秀!