0

Extreme noob. I define a CADisplayLink, then I want to invalidate it later using a UIButton. I get the error 'cannot find in scope' because (I assume) the link is initialized inside the func. Cannot figure out how to "get inside" the func to invaidate it. Code: ``` func myDisplayLink() {let displayLink = CADisplayLink(target: self, selector: #selector(myCycle)) displayLink.add(to: .current, forMode: RunLoop.Mode.default) }

@IBAction func OFF(_ sender: UIButton)
{ ????? }
```
VC25P
  • 3
  • 3

1 Answers1

0

You can declare it as an optional outside the scope of your function, at the root of your class then just initialize it in your function, like so:

class: SomeClass {

 var displayLink: CADisplayLink?

 func myDisplayLink() {
  displayLink = CADisplayLink(target: self, selector: #selector(myCycle))
  displayLink!.add(to: .current, forMode: RunLoop.Mode.default) 
 }

 @IBAction func OFF(_ sender: UIButton) {
  displayLink!.invalidate()
 }

}
SuperTully
  • 319
  • 1
  • 6
  • Thanks. When I make that change I get "Value of option type 'CADisplayLink?' must be unwrapped to refer to member 'add' of wrapped base type 'CADisplayLink'. Not sure how to 'unwrap.' – VC25P Dec 07 '20 at 21:50
  • That was my bad, I forgot to "unwrap" the optional in my code example. I updated my response, notice the ! character now. Alternatively, you can force unwrap the optional in its declaration by using a ! instead of a ? (example, var: displayLink: CADisplayLink!), then you don't need to use the ! to unwrap it later. Remember though, it's a NIL value until you initialize it, so don't refer to it unless you're sure it has a value, or unless you use conditional unwrapping. – SuperTully Dec 07 '20 at 22:17
  • Awesome! Thanks!! – VC25P Dec 07 '20 at 22:25