Search code examples
iosmultithreadingnsoperationnsoperationqueue

NSOperation userInfo Dictionary


Is there a way how to have a userInfo NSDictionary for a NSOperation?

Basically i want to assign an ID to an NSOperation, later i want to check, if this ID is already assigned to an NSOperation

- (void)processSmthForID:(NSString *)someID {

    for (NSOperation * operation in self.precessQueue.operations) {

        if ([operation.userInfo[@"id"] isEqualToString:someID]) {
            // already doing this for this ID, no need to create another operation
            return;
        }

    }

    NSOperation * newOperation = ...
    newOperation.userInfo[@"id"] = someID;

    // enqueue and execute

}

Solution

  • NSOperation is meant to be subclassed. just design your own subclass.

    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.

    read here

    I agree with @Daij-Djan about the userInfo property addition.
    This property could be implemented as an extension over NSOperation (refer to his answer for implementation).
    However, The need for an identifier for an NSOperation is a specialization of the class (you could say that the new class is an IdentifiableOperation)