iOS

[iOS] Operation 정리

Kim_Baechu 2022. 3. 7. 23:00

Operation 관련 이전 포스팅

https://baechukim.tistory.com/36

 

[iOS] Operation 알아보기

https://developer.apple.com/documentation/foundation/operation Apple Developer Documentation developer.apple.com Operation 싱글 tast와 관련된 코드와 데이터를 나타내는 추상 클래스 Overview Operation..

baechukim.tistory.com

 

Operation

작업을 객체화 -> 재사용의 이점

기본적으로 동기적(sync)

인스턴스화 -> 한번만 실행

 

기능

취소

순서지정

상태 체크 (isReady, isExecuting, isCancelled, isFinished)

KVO notifications

Qos

completionBlock

 

BlockOperation

내부에 block을 가지고 있음.

내부의 block들을 다른 쓰레드에서 처리하고 마지막에 completionBlock을 처리함

디스패치 그룹과 유사

기본 설정은 동기적 (queue로 보내서 비동기도 가능)

 

OperationQueue

GCD기반으로 구현

maxConcurrentOperationCount = n

default = -1 (시스템이 알아서), n = 1일 때 시리얼, n일 때, n개의 쓰레드 사용

operation의 품질이 높으면 Queue의 품질이 높아질 수 있음

queue.underlyingQueue의 품질이 가장 우선 적용됨

클로저, 오퍼레이션, 오퍼레이션 배열

일시중지 isSuspended

 

AsyncOperation

class AsyncOperation: Operation {
    
    enum State: String {
        case ready, executing, finished
        
        fileprivate var keyPath: String {
            return "is\(rawValue.capitalized)"
        }
    }
    
    var state = State.ready {
        willSet {
            willChangeValue(forKey: newValue.keyPath)
            willChangeValue(forKey: state.keyPath)
        }
        didSet {
            didChangeValue(forKey: oldValue.keyPath)
            didChangeValue(forKey: state.keyPath)
        }
    }

    override var isReady: Bool {
        return super.isReady && state == .ready
    }
    
    override var isExecuting: Bool {
        return state == .executing
    }
    
    override var isFinished: Bool {
        return state == .finished
    }
    
    override var isAsynchronous: Bool {
        return true
    }
    
    override func start() {
        if isCancelled {
            state = .finished
            return
        }
        main()
        state = .executing
    }
    
    override func cancel() {
        super.cancel()
        state = .finished
    }
}