Class: NSOperation
Overview
The NSOperation class is an abstract class you use to encapsulate the code and data associated with a single task. Because it is abstract, you do not use this class directly but instead subclass or use one of the system-defined subclasses (NSInvocationOperation or NSBlockOperation) to perform the actual task. Despite being abstract, the base implementation of NSOperation does include significant logic to coordinate the safe execution of your task. The presence of this built-in logic allows you to focus on the actual implementation of your task, rather than on the glue code needed to ensure it works correctly with other system objects.
Direct Known Subclasses
NSBlockOperation, NSInvocationOperation, UIActivityItemProvider
Instance Method Summary (collapse)
-
- addDependency:
Makes the receiver dependent on the completion of the specified operation.
-
- cancel
Advises the operation object that it should stop executing its task.
-
- completionBlock
Returns the block to execute when the operation’s main task is complete.
-
- dependencies
Returns a new array object containing the operations on which the receiver is dependent.
-
- init
Returns an initialized NSOperation object.
-
- isCancelled
Returns a Boolean value indicating whether the operation has been cancelled.
-
- isConcurrent
Returns a Boolean value indicating whether the operation runs asynchronously.
-
- isExecuting
Returns a Boolean value indicating whether the operation is currently executing.
-
- isFinished
Returns a Boolean value indicating whether the operation is done executing.
-
- isReady
Returns a Boolean value indicating whether the receiver’s operation can be performed now.
-
- main
Performs the receiver’s non-concurrent task.
-
- queuePriority
Returns the priority of the operation in an operation queue.
-
- removeDependency:
Removes the receiver’s dependence on the specified operation.
-
- setCompletionBlock:
Sets the block to execute when the operation has finished executing.
-
- setQueuePriority:
Sets the priority of the operation when used in an operation queue.
-
- setThreadPriority:
Sets the thread priority to use when executing the operation.
-
- start
Begins the execution of the operation.
-
- threadPriority
Returns the thread priority to use when executing the operation.
-
- waitUntilFinished
Blocks execution of the current thread until the receiver finishes.
Methods inherited from NSObject
#!, #!=, #!~, #, #==, #===, #=~, #Rational, #__callee__, #__method__, #__send__, #__type__, `, alloc, allocWithZone:, #autoContentAccessingProxy, autoload, autoload?, autorelease_pool, #awakeAfterUsingCoder:, binding, block_given?, caller, cancelPreviousPerformRequestsWithTarget:, cancelPreviousPerformRequestsWithTarget:selector:object:, catch, class, classFallbacksForKeyedArchiver, #classForCoder, #classForKeyedArchiver, classForKeyedUnarchiver, #clone, conformsToProtocol:, #copy, copyWithZone:, #dealloc, #define_singleton_method, description, display, #doesNotRecognizeSelector:, #dup, #enum_for, #eql?, #equal?, #extend, fail, #finalize, format, #forwardInvocation:, #forwardingTargetForSelector:, framework, #freeze, #frozen?, getpass, gets, global_variables, initialize, #initialize_clone, #initialize_copy, #initialize_dup, #inspect, instanceMethodForSelector:, instanceMethodSignatureForSelector:, #instance_eval, #instance_exec, #instance_of?, #instance_variable_defined?, #instance_variable_get, #instance_variable_set, #instance_variables, instancesRespondToSelector:, isSubclassOfClass:, #is_a?, iterator?, #kind_of?, lambda, load, load_bridge_support_file, load_plist, local_variables, loop, #method, #methodForSelector:, #methodSignatureForSelector:, #methods, #mutableCopy, mutableCopyWithZone:, new, #nil?, open, p, #performSelector:onThread:withObject:waitUntilDone:, #performSelector:onThread:withObject:waitUntilDone:modes:, #performSelector:withObject:afterDelay:, #performSelector:withObject:afterDelay:inModes:, #performSelectorInBackground:withObject:, #performSelectorOnMainThread:withObject:waitUntilDone:, #performSelectorOnMainThread:withObject:waitUntilDone:modes:, print, printf, #private_methods, proc, #protected_methods, #public_method, #public_methods, #public_send, putc, puts, raise, rand, readline, readlines, #replacementObjectForCoder:, #replacementObjectForKeyedArchiver:, require, resolveClassMethod:, resolveInstanceMethod:, #respond_to?, #respond_to_missing?, select, #send, setVersion:, #singleton_methods, sprintf, srand, superclass, #taint, #tainted?, #tap, test, throw, #to_plist, #to_s, trace_var, trap, #trust, #untaint, untrace_var, #untrust, #untrusted?, version
Constructor Details
This class inherits a constructor from NSObject
Dynamic Method Handling
This class handles dynamic methods through the method_missing method in the class NSObject
Instance Method Details
- (Object) addDependency(operation)
Makes the receiver dependent on the completion of the specified operation. The receiver is not considered ready to execute until all of its dependent operations have finished executing. If the receiver is already executing its task, adding dependencies has no practical effect. This method may change the isReady and dependencies properties of the receiver. It is a programmer error to create any circular dependencies among a set of operations. Doing so can cause a deadlock among the operations and may freeze your program.
- (Object) cancel
Advises the operation object that it should stop executing its task. This method does not force your operation code to stop. Instead, it updates the object’s internal flags to reflect the change in state. If the operation has already finished executing, this method has no effect. Canceling an operation that is currently in an operation queue, but not yet executing, makes it possible to remove the operation from the queue sooner than usual. In OS X v10.6 and later, if an operation is in a queue but waiting on unfinished dependent operations, those operations are subsequently ignored. Because it is already cancelled, this behavior allows the operation queue to call the operation’s start method sooner and clear the object out of the queue. If you cancel an operation that is not in a queue, this method immediately marks the object as finished. In each case, marking the object as ready or finished results in the generation of the appropriate KVO notifications. In versions of OS X prior to 10.6, an operation object remains in the queue until all of its dependencies are removed through the normal processes. Thus, the operation must wait until all of its dependent operations finish executing or are themselves cancelled and have their start method called. For more information on what you must do in your operation objects to support cancellation, see “Responding to the Cancel Command.”
- (Object) completionBlock
Returns the block to execute when the operation’s main task is complete. The completion block you provide is executed when the value returned by the isFinished method changes to YES. Thus, this block is executed by the operation object after the operation’s primary task is finished or cancelled.
- (Array) dependencies
Returns a new array object containing the operations on which the receiver is dependent. The receiver is not considered ready to execute until all of its dependent operations finish executing. Operations are not removed from this dependency list as they finish executing. You can therefore use this list to track all dependent operations, including those that have already finished executing. The only way to remove an operation from this list is to use the removeDependency: method.
- (Object) init
Returns an initialized NSOperation object. Your custom subclasses must call this method. The default implementation initializes the object’s instance variables and prepares it for use.
- (Boolean) isCancelled
Returns a Boolean value indicating whether the operation has been cancelled. Canceling an operation does not actively stop the receiver’s code from executing. An operation object is responsible for calling this method periodically and stopping itself if the method returns YES.You should always call this method before doing any work towards accomplishing the operation’s task, which typically means calling it at the beginning of your custom main method. It is possible for an operation to be cancelled before it begins executing or at any time while it is executing. Therefore, calling this method at the beginning of your main method (and periodically throughout that method) lets you exit as quickly as possible when an operation is cancelled.
- (Boolean) isConcurrent
Returns a Boolean value indicating whether the operation runs asynchronously. If you are implementing a concurrent operation, you must override this method and return YES from your implementation. For more information about the differences between concurrent and non-concurrent operations, see “Concurrent Versus Non-Concurrent Operations.” In OS X v10.6 and later, operation queues ignore the value returned by this method and always start operations on a separate thread.
- (Boolean) isExecuting
Returns a Boolean value indicating whether the operation is currently executing. If you are implementing a concurrent operation, you should override this method to return the execution state of your operation. If you do override it, be sure to generate KVO notifications for the isExecuting key path whenever the execution state of your operation object changes. For more information about manually generating KVO notifications, see Key-Value Observing Programming Guide.
- (Boolean) isFinished
Returns a Boolean value indicating whether the operation is done executing. If you are implementing a concurrent operation, you should override this method and return a Boolean to indicate whether your operation is currently finished. If you do override it, be sure to generate appropriate KVO notifications for the isFinished key path when the completion state of your operation object changes. For more information about manually generating KVO notifications, see Key-Value Observing Programming Guide.
- (Boolean) isReady
Returns a Boolean value indicating whether the receiver’s operation can be performed now. Operations may not be ready due to dependencies on other operations or because of external conditions that might prevent needed data from being ready. The NSOperation class manages dependencies on other operations and reports the readiness of the receiver based on those dependencies. If you want to use custom conditions to determine the readiness of your operation object, you can override this method and return a value that accurately reflects the readiness of the receiver. If you do so, your custom implementation should invoke super and incorporate its return value into the readiness state of the object. Your custom implementation must also generate appropriate KVO notifications for the isReady key path.
- (Object) main
Performs the receiver’s non-concurrent task. The default implementation of this method does nothing. You should override this method to perform the desired task. In your implementation, do not invoke super.If you are implementing a concurrent operation, you are not required to override this method but may do so if you plan to call it from your custom start method.
- (NSOperationQueuePriority) queuePriority
Returns the priority of the operation in an operation queue.
- (Object) removeDependency(operation)
Removes the receiver’s dependence on the specified operation. This method may change the isReady and dependencies properties of the receiver.
- (Object) setCompletionBlock(block)
Sets the block to execute when the operation has finished executing. The exact execution context for your completion block is not guaranteed but is typically a secondary thread. Therefore, you should not use this block to do any work that requires a very specific execution context. Instead, you should shunt that work to your application’s main thread or to the specific thread that is capable of doing it. For example, if you have a custom thread for coordinating the completion of the operation, you could use the completion block to ping that thread. Because the completion block executes after the operation indicates it has finished its task, you must not use a completion block to queue additional work considered to be part of that task. An operation object whose isFinished method returns YES must be done with all of its task-related work by definition. The completion block should be used to notify interested objects that the work is complete or perform other tasks that might be related to, but not part of, the operation’s actual task. A finished operation may finish either because it was cancelled or because it successfully completed its task. You should take that fact into account when writing your block code. Similarly, you should not make any assumptions about the successful completion of dependent operations, which may themselves have been cancelled.
- (Object) setQueuePriority(priority)
Sets the priority of the operation when used in an operation queue. You should use priority values only as needed to classify the relative priority of non-dependent operations. Priority values should not be used to implement dependency management among different operation objects. If you need to establish dependencies between operations, use the addDependency: method instead. If you attempt to specify a priority value that does not match one of the defined constants, this method automatically adjusts the value you specify towards the NSOperationQueuePriorityNormal priority, stopping at the first valid constant value. For example, if you specified the value -10, this method would adjust that value to match the NSOperationQueuePriorityVeryLow constant. Similarly, if you specified +10, this method would adjust the value to match the NSOperationQueuePriorityVeryHigh constant.
- (Object) setThreadPriority(priority)
Sets the thread priority to use when executing the operation. The value you specify is mapped to the operating system’s priority values. The specified thread priority is applied to the thread only while the operation’s main method is executing. It is not applied while the operation’s completion block is executing. For a concurrent operation in which you create your own thread, you must set the thread priority yourself in your custom start method and reset the original priority when the operation is finished.
- (Object) start
Begins the execution of the operation. The default implementation of this method updates the execution state of the operation and calls the receiver’s main method. This method also performs several checks to ensure that the operation can actually run. For example, if the receiver was cancelled or is already finished, this method simply returns without calling main. (In OS X v10.5, this method throws an exception if the operation is already finished.) If the operation is currently executing or is not ready to execute, this method throws an NSInvalidArgumentException exception. In OS X v10.5, this method catches and ignores any exceptions thrown by your main method automatically. In OS X v10.6 and later, exceptions are allowed to propagate beyond this method. You should never allow exceptions to propagate out of your main method.Note: An operation is not considered ready to execute if it is still dependent on other operations that have not yet finished.If you are implementing a concurrent operation, you must override this method and use it to initiate your operation. Your custom implementation must not call super at any time. In addition to configuring the execution environment for your task, your implementation of this method must also track the state of the operation and provide appropriate state transitions. When the operation executes and subsequently finishes its work, it should generate KVO notifications for the isExecuting and isFinished key paths respectively. For more information about manually generating KVO notifications, see Key-Value Observing Programming Guide. You can call this method explicitly if you want to execute your operations manually. However, it is a programmer error to call this method on an operation object that is already in an operation queue or to queue the operation after calling this method. Once you add an operation object to a queue, the queue assumes all responsibility for it.
- (Float) threadPriority
Returns the thread priority to use when executing the operation.
- (Object) waitUntilFinished
Blocks execution of the current thread until the receiver finishes. The receiver should never call this method on itself and should avoid calling it on any operations submitted to the same operation queue as itself. Doing so can cause the operation to deadlock. It is generally safe to call this method on an operation that is in a different operation queue, although it is still possible to create deadlocks if each operation waits on the other. A typical use for this method would be to call it from the code that created the operation in the first place. After submitting the operation to a queue, you would call this method to wait until that operation finished executing.