Junior — Middle
What happens inside NSOperation when the cancel method is called and how is its logic implemented at a low level?
sobes.tech AI
Answer from AI
Calling the cancel method on an NSOperation object sets an internal cancellation flag. This flag signals that the operation should be interrupted if possible.
At a low level, NSOperation does not forcibly interrupt code execution — responsibility for checking the cancellation state lies with the operation's code itself. Typically, within an overridden main method or an operation block, the isCancelled property is periodically checked, and if it is true, the operation terminates correctly.
Example:
override func main() {
if isCancelled { return }
// Perform task
for i in 0..<100 {
if isCancelled { return }
// work
}
}
Thus, cancel changes the state of the operation, and the operation itself must respond to this state to terminate correctly. This prevents issues with thread interruption and ensures safe management of task lifecycle.