Skip to content

Latest commit

ย 

History

History
107 lines (90 loc) ยท 2.01 KB

defer.md

File metadata and controls

107 lines (90 loc) ยท 2.01 KB

defer๋ž€ ๋ฌด์—‡์ธ์ง€ ์„ค๋ช…ํ•˜์‹œ์˜ค.

๋‹ต๋ณ€


ํ•จ์ˆ˜ ์•ˆ์—์„œ ์ž‘์„ฑ ์œ„์น˜์™€ ์ƒ๊ด€์—†์ด ํ•จ์ˆ˜๊ฐ€ ์ข…๋ฃŒ๋˜๊ธฐ ์ „์— ์‚ฌ์šฉ๋˜๋Š” ํด๋กœ์ € ์ž…๋‹ˆ๋‹ค.
defer๋ฅผ ์˜์–ด ๊ทธ๋Œ€๋กœ ํ•ด์„ํ•˜์—ฌ ํ•จ์ˆ˜ ์ข…๋ฃŒ ์ง์ „๊นŒ ์‹คํ–‰์„ ๋ฏธ๋ฃจ๋‹ค ๋ผ๊ณ  ์ƒ๊ฐํ•˜์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์‚ฌ์šฉ๋ฒ•

ํ•จ์ˆ˜ ์•ˆ์—์„œ ์–ด๋””์„œ๋“  defer๋ฅผ ๊ตฌํ˜„ํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

func testDefer() {
  print("#1")
  
  defer { print("#2") }
  
  print("#3")
}

์ผ๋ฐ˜์ ์ธ ์‹คํ–‰ ์ˆœ์„œ์— ์˜ํ•˜๋ฉด

#1
#2
#3

์ด ๋งž๋Š” ์ˆœ์„œ๊ฒ ์ง€๋งŒ #2์€ defer ํด๋กœ์ €๋ฅผ ์‚ฌ์šฉํ–ˆ์œผ๋ฏ€๋กœ ์œ„ ํ•จ์ˆ˜์˜ ์‹คํ–‰ ๊ฒฐ๊ณผ๋Š”

#1
#3
#2

์˜ ์ˆœ์„œ๋กœ ์ถœ๋ ฅ๋ฉ๋‹ˆ๋‹ค.

์ฃผ์˜์ 

  1. defer๋ฅผ ์ฝ๊ธฐ ์ „์— ํ•จ์ˆ˜๊ฐ€ ์ข…๋ฃŒ๋˜๋ฉด defer๋Š” ์‹คํ–‰๋˜์ง€ ์•Š๋Š”๋‹ค.
func testDefer() {
  print("#1")
  return
  
  defer { print("#2") }
  
  print("#3")
}

์œ„์™€๊ฐ™์ด defer๊ฐ€ ์ฝํžˆ๊ธฐ๋„ ์ „์— ์ข…๋ฃŒ๋œ ๊ฒฝ์šฐ defer๋Š” ์‹คํ–‰๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ์œ„ ํ•จ์ˆ˜์˜ ์ถœ๋ ฅ์€

#1

์ด ๋ฉ๋‹ˆ๋‹ค.

2.defer์˜ ์‹คํ–‰ ์ˆœ์„œ๋Š” ์ฝ์€ ์ˆœ์„œ์˜ ์—ญ์ˆœ์ด๋‹ค.
stack์— ๋‹ด๊ฒจ์ ธ์žˆ๋‹ค๊ฐ€ ํ˜ธ์ถœ์ด ๋˜๋Š” ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.

func testDefer() {
  defer { print("#1") }
  defer { print("#2") }
  defer { print("#3") }
}

์œ„ ํ•จ์ˆ˜์˜ ๊ฒฝ์šฐ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ถœ๋ ฅ๋ฉ๋‹ˆ๋‹ค.

#3
#2
#1
  1. defer๋Š” ์ค‘์ฒฉ์ด ๊ฐ€๋Šฅํ•˜๋ฉฐ ๋ฐ”๊นฅ์ชฝ ๋ถ€ํ„ฐ ์‹คํ–‰๋œ๋‹ค.
func testDefer() {
    defer {
        defer {
            defer {
                print("defer #3")
            }
            print("defer #2")
        }
        print("defer #1")
    }
}

์œ„ ํ•จ์ˆ˜์˜ ์ถœ๋ ฅ ๊ฒฐ๊ณผ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

#1
#2
#3

๊ทธ๋ ‡๋‹ค๋ฉด ์–ธ์ œ ์‚ฌ์šฉํ•˜๋Š”๊ฐ€??

ํ•จ์ˆ˜ ์ข…๋ฃŒ ์ „ ๋ณ€์ˆ˜๋‚˜ ์ƒ์ˆ˜๋ฅผ ์ฒ˜๋ฆฌ์šฉ์œผ๋กœ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.
์˜ˆ๋ฅผ๋“ค์–ด NSLock ์ด์šฉ์‹œ

let myLock: NSLock = .init()

func fetchData() {
    myLock.lock()
    
    defer { myLock.unlock() }
    
    if data == nil { return }
    
    //์ดํ›„ ์ž‘์—… ~.~

์ฐธ๊ณ ํ•œ ๋ธ”๋กœ๊ทธ

https://babbab2.tistory.com/80