iOS) Operation Queue

Havi·2020년 9월 14일
1

본 블로그는 개인적인 공부 및 저장의 용도 작성됐습니다.

  • 단일 작업과 관련된 코드 및 데이터를 나타내는 추상 클래스
  • Operation Queue는 Operation을 관리
  • Queue에 추가된 동작은 제거 불가 but 취소 가능
  • GCD와 달리 FIFO가 아님 -> 수행할 수 있는 충분한 자원이 있는 한 실행 준비시 바로 실행

GCD와의 차이점

  1. Pause, Cancel, Resume 가능
  2. Dependency 추가 가능
    • 모든 dependencies가 true로 finish 되기 전까지 작업을 실행하지 않음
  3. 동시 작업 갯수 설정 가능
  4. ready ,executing or finished등의 상태를 monitor할 수 있음

Operation Queue 사용법

//선언법
//Main Operation Queue 선언
let mainOper = OperationQueue.main

//Custom Operation Queue 선언
let custumOper = OperationQueue()

custumOper.name = "Custom Queue"
custumOper.qualityOfService = .default


// Add Block Operation
// 1. 블록 선언 후 추가
//instance of operation subclass
let operation = BlockOperation {
    // something to do
}
//block: () -> void
custumOper.addOperation(operation)

//2. 선언과 동시에 추가
//add a block : { code }
custumOper.addOperation {
    // something to do
}


//multiple tasks
var opers = [Operation]()

opers.append(operation)
opers.append(operation)

//ops: [Operation], waitUntilFinished: Bool
custumOper.addOperations(opers, waitUntilFinished: false)


// 3 operations may execute at once
custumOper.maxConcurrentOperationCount = 3 

//일시정지
custumOper.isSuspended = true
//다시시작
custumOper.isSuspended = false

참조
https://riptutorial.com/swift/example/13293/running-tasks-in-an-operationqueue
https://stackoverflow.com/questions/10373331/nsoperation-vs-grand-central-dispatch/40064466#40064466

profile
iOS Developer

0개의 댓글