Selector

Selector

๐Ÿ’ก ์†์„ฑ์— ์ ‘๊ทผํ•˜๊ฑฐ๋‚˜ ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ, ๊ฐ€๋ฆฌํ‚ค๋Š” ์—ญํ• ๋งŒ ํ•œ๋‹ค. ์ฝ”๋“œ ์˜์—ญ์˜ ๋ฉ”๋ชจ๋ฆฌ ์ฃผ์†Œ๋ฅผ ๊ฐ€๋ฆฌ์ผœ์„œ, ์—ฐ๊ฒฐ์‹œํ‚ค๋Š” ๊ธฐ์ˆ ์ด๋‹ค.

  • ํด๋กœ์ €์™€ ์œ ์‚ฌํ•˜๋‹ค.

    • ๋‹ค๋งŒ, ํ˜ธ์ถœ์€ ํ•  ์ˆ˜ ์—†๊ณ , ํŠน์ • ์ด๋ฒคํŠธ๋ฅผ ์ „๋‹ฌํ•ด์ฃผ๋Š” ์—ญํ• ์ด๋‹ค.

  • ๋ฉ”์„œ๋“œ ์ฃผ์†Œ๋ฅผ ํ†ตํ•ด ๋ฉ”์„œ๋“œ๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค.

    • ๋งค๊ฐœ๋ณ€์ˆ˜์— ๋ฉ”์„œ๋“œ์˜ ์ด๋ฆ„์ด ๋“ค์–ด๊ฐ„๋‹ค. (์ฃผ์†Œ)

    • ๋‚ด๋ถ€์ ์œผ๋กœ Objective-C๋กœ ๊ตฌํ˜„๋˜์–ด์žˆ๋‹ค.

  • ๊ตฌ์กฐ์ฒด ํƒ€์ž…์ด๋ฏ€๋กœ ๊ฐ€๋ฆฌํ‚ฌ ์ˆ˜๋งŒ ์žˆ๊ณ , ์‹คํ–‰์€ ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค.

์˜ˆ์‹œ

class Dog {
    var num = 1.0

    @objc var doubleNum: Double {
        get {
            return num * 2.0
        }
        set {
            num = newValue / 2.0
        }
    }

    @objc func run() {
        print("๋‹ฌ๋ฆฌ๋‹ค")
    }
}

// (๊ณ„์‚ฐ)์†์„ฑ์„ ๊ฐ€๋ฅดํ‚ฌ๋•Œ
let eyesSelector = #selector(**getter**: Dog.doubleNum)    // ๊ณ„์‚ฐ(์ฝ๊ธฐ) ์†์„ฑ
let nameSelector = #selector(**setter**: Dog.doubleNum)    // ๊ณ„์‚ฐ(์“ฐ๊ธฐ) ์†์„ฑ

// ๋ฉ”์„œ๋“œ๋ฅผ ๊ฐ€๋ฅดํ‚ฌ๋•Œ
let runSelector = #selector(Dog.run) // ํ”ํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ
  • ํด๋ž˜์Šค, Objective-C ํ”„๋กœํ† ์ฝœ์— ํฌํ•จ๋œ ๋ฉค๋ฒ„์—๋งŒ ์ ์šฉ์ด ๊ฐ€๋Šฅํ•˜๋‹ค. (๊ตฌ์กฐ์ฒด์—์„œ ์ ์šฉ ๋ถˆ๊ฐ€๋Šฅ)

  • ๋‚ด๋ถ€์ ์œผ๋กœ Objective C ํ”„๋ ˆ์ž„์›Œํฌ๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์— @objc ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด์•ผํ•œ๋‹ค.

์˜ˆ์‹œ

class ViewController: UIViewController {
    
    lazy var myButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("MyButton", for: .normal)
        button.frame = CGRect(x: 0.0, y: self.view.frame.height - 150, width: view.frame.width, height: 50.0)
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(myButton)
        myButton.addTarget(self, action: **#selector(ViewController.doSomething(_:))**, for: .touchUpInside)
                // myButton.addTarget(self, action: #selector(doSomething), for: .touchUpInside)
                    // self๋ฅผ ์•ž์—์„œ ์‚ฌ์šฉํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— ViewController๋Š” ์ƒ๋žตํ•  ์ˆ˜ ์žˆ๋‹ค.
    }
    
    // ์…€๋ ‰ํ„ฐ๋Š” ์˜ค๋ธŒ์ ํ‹ฐ๋ธŒC์—์„œ ์ธ์‹ํ•  ์ˆ˜ ์žˆ๋Š” ์†์„ฑ/๋ฉ”์„œ๋“œ๋งŒ ๊ฐ€๋ฅดํ‚ฌ ์ˆ˜ ์žˆ์Œ
    **@objc** func doSomething(_ sender: Any) {

    }
    
}
  • addTarget

    • ์ฝ”๋“œ๋กœ ๋ฒ„ํŠผ์„ ๋งŒ๋“ค์—ˆ์„ ๋•Œ, ์–ด๋–ค ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰์‹œํ‚ฌ์ง€ ๊ฒฐ์ •ํ•ด์•ผํ–”๋‹ค.

    • ์ฆ‰, ๋ฒ„ํŠผ์„ ๋ˆŒ๋ €์„ ๋•Œ, ์–ด๋–ค ์ธ์Šคํ„ด์Šค๋ฅผ ์‹คํ–‰์‹œํ‚ฌ์ง€ ์ ์–ด์ค„ ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค. ์ด๋•Œ ๋งค๊ฐœ๋ณ€์ˆ˜์— selector๋ฅผ ํ†ตํ•ด ์ˆ˜ํ–‰ํžŒ๋‹ค.

Last updated