Ios autorelase池访问方法中的Swift闭包
这是示例代码Ios autorelase池访问方法中的Swift闭包,ios,swift,nsautoreleasepool,Ios,Swift,Nsautoreleasepool,这是示例代码 func anyMethod() { // Nothing here } var myVariable = "" autoreleasepool { anyMethod() // This should show error print(myVariable) // This should show error } 它应该显示错误 在闭包中调用方法“anyMethod”需要显式的“self”。以使捕获语义显式 但是我能够调用任何方法,而无需
func anyMethod() {
// Nothing here
}
var myVariable = ""
autoreleasepool {
anyMethod() // This should show error
print(myVariable) // This should show error
}
它应该显示错误
在闭包中调用方法“anyMethod”需要显式的“self”。以使捕获语义显式
但是我能够调用任何方法
,而无需self,我想知道为什么这不会显示错误
为什么没有self
编辑
复制粘贴此类以重新生成
import Foundation
import UIKit
class AppGlobalManager:NSObject {
var currentUserID:String?
//Please ignore the method content as it is not the question
func appendLog(string:String?) {
print("LOG:",string)
}
func autoRelaseTest() {
autoreleasepool {
appendLog(string: "Any Log") // NO ERROR
}
}
func normalFunctionTest () {
normalFuncWithClosure {
appendLog(string: "Test") //Call to method 'appendLog' in closure requires explicit 'self.' to make capture semantics explicit
}
}
func normalFuncWithClosure (completion:@escaping() -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
completion()
}
}
}
调用实例方法或引用闭包中的实例属性需要显式的
self
,如果该闭包被传递给使用@转义
参数的函数。这就明确了self
可能在函数调用的持续时间之外被捕获
如果功能参数不是@escaping
,则不需要显式self
以下是一个独立的示例:
func funcTakingNonescapingClosure(_ closure: () -> Void) { }
func funcTakingEscapingClosure(_ closure: @escaping () -> Void) { }
class Foo {
func anyMethod() { }
var myVariable = ""
func test() {
funcTakingNonescapingClosure {
anyMethod() // No error
print(myVariable) // No error
}
funcTakingEscapingClosure {
anyMethod()
// Call to method 'anyMethod' in closure requires explicit 'self.'
// to make capture semantics explicit
print(myVariable)
// Reference to property 'myVariable' in closure requires explicit
// 'self.' to make capture semantics explicit
}
}
}
在您的示例中,
Dispatch.main.async
接受转义闭包,但是autorelease
没有。为什么要显示错误anyMethod()
和myVariable
不是类的实例方法/属性。您的代码中没有“self”。@MartinR先生,如果我添加DispatchQueue.main.async{anyMethod()}
则在autoreleasepool旁边是“self”。这意味着它是方法的实例class@MartinR先生,添加的截图可能会有帮助。我无法在您的代码中看到类,请发布一个但最有可能的区别是:DispatchQueue.main.async
接受@escaping闭包参数,而autoreleasepool
不接受。@martiner先生。好了,你能看一下吗