简体   繁体   中英

How to do async task in non-concurrent custom nsoperation

Maybe I let NSOperation to play a wrong role in non-concurrent job. My requirement is , I want to do a lot of async jobs, but I want them to be completed in order. When task1 is finished after the async callback, task2 can be take into work now. And I make all the task a NSOperation . However, NSOperation is used to multiple thread programming most time. Is my choice wrong. But it remind me to think more about the NSOperation in this case, we can't manage manually the isFinished and isExecute in a sync block since the operation have been release in non-concurrent nsoperation,it means i couldnot use the powerful operation queue to automatically manage the task.Any idea?Thanks for your answer..

edit with code :

-(void)main {
    [super main];
    self.isOperationExcuting = YES;
    self.isOperationFinished = NO;
    WEAKSELF
    [self query:^(NSArray *array, NSError *error) {
        //I set my custom property, but it do not cause my NSOperation to be finished
        weakSelf.isOperationFinished = YES;
        weakSelf.isOperationExcuting = NO;
    }];
}
-(void)query:(void (^)(NSArray *array, NSError *error))block {
    BmobQuery *query = [BmobQuery queryWithClassName:@"Room"];
    [query findObjectsInBackgroundWithBlock:block];
}
-(BOOL)isFinished {
    return self.isOperationFinished;
}
- (BOOL)isExecuting {
    return self.isOperationExcuting;
}
- (void)start {
    [super start];
    NSLog(@"start");
}
- (void)cancel {
    [super cancel];
    NSLog(@"cancel");
}

Just make all added operations serial by setting maxConcurrentOperationCount to 1 .

NSOperationQueue* queue = [[ NSOperationQueue alloc ] init];
queue.maxConcurrentOperationCount = 1;

[queue addOperation:operation1];
[queue addOperation:operation2];
[queue addOperation:operation3];

NSOperationQueue

The NSOperationQueue class regulates the execution of a set of NSOperation objects. After being added to a queue, an operation remains in that queue until it is explicitly canceled or finishes executing its task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM