Search code examples
iosobjective-cafnetworkingnsoperationqueue

NSOperationQueue currentQueue not working


I am trying to run AFURLConnectionOperation seen below on the currentQueue as I want to keep my main thread free for user interatoin, however nothing happens when I call mainQeue.

However if I call the same AFURLConnectionOperation on mainQueue it works perfectly.

Pleas see following code

// Send Batch
        NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:mutableOperations progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
            NSLog(@"%lu of %lu complete", (unsigned long)numberOfFinishedOperations, (unsigned long)totalNumberOfOperations);
        } completionBlock:^(NSArray *operations) {
            // check batch response
            NSError *error;
            for (AFHTTPRequestOperation *op in operations) {
                if (op.isCancelled){
                    return ;
                }
                if (op.responseObject){
                    // Current JSON Batch complete
                    NSMutableArray *jsonObject = [NSJSONSerialization JSONObjectWithData:op.request.HTTPBody options:kNilOptions error:&error];
                    // Update sent_flag using current chunk
                    [[SyncModel sharedInstance] updateSentFlag:jsonObject];
                }
                if (op.error){
                    error = op.error;
                    NSLog(@"Error == %@", error);
                }
            }
        }];

Then finally I call one or the other of the following code

[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO]; // this works
[[NSOperationQueue currentQueue] addOperations:operations waitUntilFinished:NO]; // this dose not work

Solution

  • The reason is

    You can use this method from within a running operation object to get a reference to the operation queue that started it. Calling this method from outside the context of a running operation typically results in nil being returned.

    So,I guess,if you log [NSOperationQueue currentQueue],it is nil

    If you want a new queue,use

    [[NSOperationQueue alloc] init];