강의

멘토링

커뮤니티

Inflearn Community Q&A

xpflxhfl948142's profile image
xpflxhfl948142

asked

Alan iOS Concurrency - Understanding Dispatch Queues and Operation Queues

1) Tasks that must be processed in the main queue 2) Notes on the sync method 3) Be careful of weak and strong capture 4) Reason for the existence of completion handlers 5) How to make a synchronous function look like an asynchronous function

동기적 함수를 비동기적 함수로 바꾸는 부분에서 질문 있습니다

Resolved

Written on

·

270

1

func asyncTiltShift(_ inputImage: UIImage?, runQueue: DispatchQueue, completionQueue: DispatchQueue, completion: @escaping (UIImage?, Error?) -> ()) {
    
    runQueue.async {
        var error: Error?
        error = .none
        
        let outputImage = tiltShift(image: inputImage)
        
        completionQueue.async {
            completion(outputImage, error)
        }
    }
}

runQueue는 이미 비동기로 돌아가고 있는데 굳이 completionQueue에서 다시 한번 더 비동기로 돌아가게 만드는 이유가 무엇인가요?

 

강의 너무 잘 듣고 있습니다 :)

iosswift

Answer 2

2

xpflxhfl948142님의 프로필 이미지
xpflxhfl948142
Questioner

빠른 답변 감사합니다!

2

allen님의 프로필 이미지
allen
Instructor

안녕하세요 본성 님!

원하시면 굳이 comletionQueue를 만드실 필요가 없습니다. 다만, 일반적으로 콜백함수가 main큐에서 일해야하는 경우가 많기 때문에 함수를 그런식으로 설계했을 뿐입니다.

func asyncTiltShift(_ inputImage: UIImage?, runQueue: DispatchQueue, completionQueue: DispatchQueue, completion: @escaping (UIImage?, Error?) -> ()) {
    
    runQueue.async {
        var error: Error?
        error = .none
        
        let outputImage = tiltShift(image: inputImage)
        
        completionQueue.async {
            completion(outputImage, error)
        }
    }
}

위처럼 하셔도 되고,

아래처럼 completionQueue없이 설계하신 다음

func asyncTiltShift(_ inputImage: UIImage?, runQueue: DispatchQueue, completion: @escaping (UIImage?, Error?) -> ()) {
    
    runQueue.async {
        var error: Error?
        error = .none
        
        let outputImage = tiltShift(image: inputImage)
       
        completion(outputImage, error)
    }
}

 

호출할때 이런식으로 하셔도 되겠죠.

ayncTiltShift(someImage, runQueue: someQueue) { image, error in
       DispatchQueue.main.async {
              // image처리 관련 코드
       }
}


일반적으로 비동기적인 일이 끝나고 메인 쓰레드로 보낼일이 많으니.. 함수 설계에서, 완료된 콜백함수를 실행시키는 큐를 넣을 수 있도록 만들 었을 뿐입니다.

감사합니다. :)

xpflxhfl948142's profile image
xpflxhfl948142

asked

Ask a question