- GCD에서 DispatchWorkItem을 만드는것과 크게 다르지 않음
- DispatchWorkItem도 실행할 코드 블록을 객체화해둔 것
- Operation과 거의 비슷한 기능을 하고 있음
- DispatchWorkItem보다 Operation이 먼저 등장
- OperationQueue의 사용에 있어서도 차이가 있음
- Operation과 OperationQueue에서는 객체지향적으로 설계를 했기 때문에 좀 더 세부적인 스케쥴링이 가능
Oepration
class Operation : NSObject
- Oeperation은 추상클래스
- 항상 이를 상속받는 타입을 사용해야함
- 하위 클래스는 커스텀 클래스로 직접 만들어주는 방법이 있고
- 앞서 살펴본 코드처럼 BlockOperation이라는 하위 클래스를 사용하는 방법이 있음
Operation 만들기
class BlockOperation : Operation
- BlockOperation을 활용하여 이렇게 Operation을 만들수 있음
let operation = BlockOperation {
// some code
}
// BlockOperation의 메서드
operation.addExecutionBlock {
// some code to be executed after the operation.
}
// Operation의 프로퍼티
operation.completionBlock = {
// some code to be executed after the operation and executionBlocks
}
- 여기까지는 DispatchWorkItem과 비슷
- 그런데!
addExecutionBlock(() -> Void)
라는 메서드가 등장함
- 이 메서드 호출하면 Operation이 끝난 후에 원하는 코드를 실행해줄 수 있음
completionBlock
- Operation의 프로퍼티에 코드블록을 할당하면 Operation과 연관된 excutionBlock들이 모두 실행된 다음에 실행시킬 수 있음
Operation 실행하기