Очередь делегатов NSURLSession

Это кажется странным. Кажется, я не могу успешно установить NSURLSession delegateQueue при создании.

- (void)viewDidLoad
{
    [super viewDidLoad];

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

    NSLog(@"The queue before: %@", queue);
    NSLog(@"Max op Count before: %i", queue.maxConcurrentOperationCount);

    NSURLSession *session = [NSURLSession sessionWithConfiguration:nil
                                                          delegate:self
                                                     delegateQueue:queue];

    NSLog(@"The queue after: %@", session.delegateQueue);
    NSLog(@"Max op Count after : %i", session.delegateQueue.maxConcurrentOperationCount);
}

Это приводит к следующему результату.

The queue before: <NSOperationQueue:   0x16d99160>{name = 'NSOperationQueue 0x16d99160'}
Max op Count before: 5
The queue after: <NSOperationQueue: 0x16d77a50>{name = 'NSOperationQueue 0x16d77a50'}
Max op Count after : 1

Похоже, мой delegateQueue игнорируется. Я пробовал как на устройстве, так и на симуляторе. Я не нашел никакой документации, которая объясняла бы это. У кого-нибудь есть понимание?


person Drewsmits    schedule 29.09.2013    source источник


Ответы (2)


Похоже, несмотря на то, что говорит геттер для delegateQueue, NSURLSession действительно использует ваш NSOperationQueue. Я добавил KVO для свойства «операции» в очереди:

[queue addObserver:self forKeyPath:@"operations" options:NSKeyValueObservingOptionNew context:NULL];

И добавил следующий метод:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"%@%@", object, change);
    NSOperationQueue *queue = (NSOperationQueue *)object;

    NSLog(@"The queue in KVO: %@", queue);
    NSLog(@"Max op Count in KVO: %i", queue.maxConcurrentOperationCount);

    NSLog(@"%@", self.session.delegateQueue);

}

И печатает:

2013-09-29 07:45:13.751 sotest1[17214:1403] <NSOperationQueue: 0x895e0c0>{name = 'NSOperationQueue 0x895e0c0'}
2013-09-29 07:45:13.757 sotest1[17214:4207] <NSOperationQueue: 0x98a0940>{name = 'NSOperationQueue 0x98a0940'}{
    kind = 1;
    new =     (
        "<NSBlockOperation: 0x9a52370>"
    );
}
2013-09-29 07:45:13.757 sotest1[17214:4207] The queue in KVO: <NSOperationQueue: 0x98a0940>{name = 'NSOperationQueue 0x98a0940'}
2013-09-29 07:45:13.757 sotest1[17214:4207] Max op Count in KVO: 5

Таким образом, вы можете видеть, что делегат действительно обрабатывается вашей очередью, несмотря на то, что геттер говорит об обратном. Странный.

Кстати, то, как вы это делаете, точно так же делает и AFNetworking, что в целом является хорошим знаком: https://github.com/AFNetworking/AFNetworking/blob/master/AFNetworking/AFURLSessionManager.m#L287

person ksimons    schedule 29.09.2013

Я подтверждаю проблему на своей стороне. Я пытался установить очередь из 1 элемента, как и вы, используя maxConcurrentOperationCount=1 в сеансе. Я вижу несколько задач, выполняющихся одновременно, как описано в журнале ниже в (URLSession:didWriteData:totalBytesWritten ):

NSLog(@"Download %.2f%% task=%d - operationInQueue=%d maxOperation=%d ", result, [downloadTask taskIdentifier], [self.bkgQueue operationCount],[self.bckQueue maxConcurrentOperationCount]);

Download 1.80% task=2 - operationInQueue=2 maxOperation=1 
Download 1.15% task=1 - operationInQueue=1 maxOperation=1 
Download 1.49% task=1 - operationInQueue=1 maxOperation=1 
Download 1.51% task=1 - operationInQueue=1 maxOperation=1 
Download 1.14% task=0 - operationInQueue=1 maxOperation=1 
Download 3.90% task=2 - operationInQueue=2 maxOperation=1 
Download 1.14% task=0 - operationInQueue=1 maxOperation=1 
Download 1.85% task=1 - operationInQueue=1 maxOperation=1 
Download 1.87% task=1 - operationInQueue=1 maxOperation=1 

Я также пытался увеличить это число, и количество запросов в моей очереди было равно 1. Кажется, он сам управляет очередью.

person Nicolas Lauquin    schedule 04.10.2013