简体   繁体   中英

Difference between weak self vs weak self()

What is the difference between passing [weak self] as an argument to a closure vs passing [weak self] ()

For example :

dispatch_async(dispatch_get_main_queue()) { [weak self] in 
     //Some code here
}

v/s

dispatch_async(dispatch_get_main_queue()) { [weak self] () -> Void in
     //Some code here
}

You do not pass [weak self] () as an argument to a closure.

  • [weak self] is a capture list and precedes the
  • parameter list/return type declaration () -> Void

in the closure expression.

The return type or both parameter list and return type can be omitted if they can be inferred from the context, so all these are valid and fully equivalent:

dispatch_async(dispatch_get_main_queue()) { [weak self] () -> Void in 
    self?.doSomething()
}

dispatch_async(dispatch_get_main_queue()) { [weak self] () in 
    self?.doSomething()
}

dispatch_async(dispatch_get_main_queue()) { [weak self] in 
    self?.doSomething()
}

The closure takes an empty parameter list () and has a Void return type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM