NSOperation
The secret to making apps snappy is to offload as much unnecessary work to the background as possible, and in this respect, the modern Cocoa developer has two options: Grand Central Dispatch and NSOperation. This article will primarily focus on the latter, though it’s important to note that the two are quite complementary (more on that later).
NSOperation is an abstract class for a single unit of work. It manages state, priority, dependencies, and cancellation in a thread-safe way. Use NSBlockOperation or NSInvocationOperation for simple cases without subclassing.
NSOperationQueue handles execution as a priority queue, running operations FIFO but with higher-priority ones first. It limits concurrent operations via maxConcurrentOperationCount.
State flows from ready to executing to finished, using KVO. Cancel operations early to avoid waste; set cancelled and finished to true, executing to false.
Priorities: VeryLow to VeryHigh for queue order.
Quality of Service: UserInteractive, UserInitiated, Utility, Background, or Default for resource allocation.
Asynchronous operations run in background; deprecated concurrent property. Dependencies ensure order: addDependency so one finishes before another starts. Avoid cycles. completionBlock runs once when done.
Use GCD for simple async; NSOperation for structured, repeatable tasks with state. They complement each other.
Category:
Tags:
Year: