Compound NSOperation. It is a bad idea?

For the iOS4.X application I'm working on, we often need to make an HTTP request, then parse the results and do something with the results, etc.

To do this, I created the NSOperation class, which allows you to create NSOperations using the NSOperation queue. Is there a problem using NSOperationQueues for small things like this. Some told me that queues should be more permanent.

I do not expect nesting to be more than two levels in our application.

Here is an example of such use:

@implementation CompositeOperation

- (id)initWithOperations:(NSArray *)operations {
    if ((self = [super init])) {
        operations_ = [operations retain];
        [[operations_ lastObject] addObserver:self forKeyPath:@"isFinished" options:NSKeyValueObservingOptionNew context:nil];

    }
    return self;
}

-(void)dealloc {
    [operations_ release];
    [operationQueue_ release];
    [super dealloc];
}

- (BOOL)isConcurrent {
    return YES;
}

@synthesize isExecuting = isExecuting_;
@synthesize isFinished = isFinished_;
@synthesize operations = operations_;

- (void) start {
    if (![self isCancelled]) {
        operationQueue_ = [[NSOperationQueue alloc] init];
        // TODO: Add code to execute this serially
        [operationQueue_ addOperations:operations_ waitUntilFinished:NO];
    }
}

- (void)cancel {
    if (operationQueue_) {
        [operationQueue_ cancelAllOperations];
    }
    [super cancel];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"isFinished"] && object == [operations_ lastObject]) {
        [self setIsFinished:YES];
    }
}

@end

Thanks Mike

+3
source share
1 answer

, , , : CompositeOperations.

: , COSimpleOperation , COCompositeOperation.

- - :

COSimpleOperation - NSOperation . .

- , . @mikelikespie:

, , , .

..., .

parallel sequential.

, :

NSArray *operations = @[ 
    operation1, operation2, operation3 
]; // each operation is NSOperation <COOperation> *

COCompositeOperation *parallelOperation = [[COCompositeOperation alloc] initWithOperations:operations];

, COCompositeOperation , COSequence:

: - . COCompositeOperation , COSequence, , , .

, : , NSOperations COSimpleOperation COCompositeOperation <COOperation>:

, 3 :

  • , , ( [NSOperation cancel]).

, !

, . [NSNull null] .


"", " ". , , , : ReactiveCocoa Promises PromiseKit, , , . - NSOperation/NSOperationQueue, .

P.S. , SO, , , @mikelikespie 4 .

+2

Source: https://habr.com/ru/post/1786581/


All Articles