isCancelled
라는 프로퍼티가 있었음취소
되었다는 말취소
할 수 있다operation.cancel()
cancel()
이라는 메서드를 가지고 있음
isCancelled
상태로 만들어줄 수 있음cancel()
메서드는 현재 실행 중인 Operation의 동작을 직접적으로 (강제로) 취소시켜주지는 않음 ⁉️isCancelled
프로퍼티의 값만 True로 변경해주는 메서드
cancel()
을 호출한 후, 상태의 변경을 나타내는 isCancelled
라는 프로퍼티를 추적하는 것을 통해서 작업을 관리해주면 됨class myOperation1 : Operation {
override func main() {
print("op1 (🐭) working....")
for i in 1...10 {
print("🐭")
}
}
}
class myOperation2 : Operation {
override func main() {
print("op2 (🐶) working....")
for i in 1...10 {
if self.isCancelled {
break
}
print("🐶")
}
}
}
class myOperation3 : Operation {
override func main() {
print("op3 (🍉) working....")
for i in 1...10 {
print("🍉")
}
}
}
let op1 = myOperation1()
let op2 = myOperation2()
let op3 = myOperation3()
op1.completionBlock = {
print("op1 (🐭) completed")
}
op2.completionBlock = {
print("op2 (🐶) completed")
}
op3.completionBlock = {
print("op3 (🍉) completed")
}
let opsQue = OperationQueue()
opsQue.addOperations([op1, op2, op3], waitUntilFinished: false)
DispatchQueue.global().asyncAfter(deadline: .now()) {
opsQue.cancelAllOperations()
}
op1 (🐭) working....
op3 (🍉) working....
op2 (🐶) working....
🐭
🍉
op2 (🐶) completed
🐭
🍉
🍉
🐭
start()
메서드를 호출하며 직접 실행 시켜줄 때와 OperationQueue
를 사용할 때로 나누어서 생각동기(synchronous)일 때는 Operation을 실행한 현재의 스레드에서
작업을 처리하게 됨비동기(asynchronous)일 때에는 새로운 스레드
를 만들어서 작업을 처리하게 됨OperationQueue
에 넣어서 작업을 처리하게 하면isAsynchronous
의 값과는 상관없이 모두 새로운 스레드를 만들어 작업을 처리함
Operation의 isAsynchronous
프로퍼티의 기본값은 false
즉 아무런 설정을 해주지 않았다면 동기(synchronous)로 동작한다는 뜻
만약 비동기(asynchronous)로 동작하는 Operation이 필요하다면 Custom하여 Operation을 만들어주어야 함