NSURLSession委派队列

Dre*_*its 9 objective-c 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);
}
Run Code Online (Sandbox Code Playgroud)

这导致以下输出.

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
Run Code Online (Sandbox Code Playgroud)

看起来我delegateQueue被忽略了.我已尝试过该设备以及模拟器.我还没有找到任何可以解释这一点的文档.有没有人有任何见解?

ksi*_*ons 5

看起来,尽管delegateQueue的getter说,NSURLSession确实使用了你的NSOperationQueue.我为队列中的"operations"属性添加了KVO:

[queue addObserver:self forKeyPath:@"operations" options:NSKeyValueObservingOptionNew context:NULL];
Run Code Online (Sandbox Code Playgroud)

并添加了以下方法:

- (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);

}
Run Code Online (Sandbox Code Playgroud)

它打印:

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
Run Code Online (Sandbox Code Playgroud)

所以你可以看到你的队列确实处理了委托,尽管事实上getter说不然.奇怪的.

顺便说一下,你正在做的事情也正是AFNetworking所做的,这通常是一个好兆头:https://github.com/AFNetworking/AFNetworking/blob/master/AFNetworking/AFURLSessionManager.m#L287