(void)observeValueForKeyPath:(NSString )keyPath ofObject:(id)object change:(NSDictionary<NSString ,id> )change context:(void )context {
if ([object isKindOfClass:[NSURLSessionTask class]] || [object isKindOfClass:[NSURLSessionDownloadTask class]]) {
if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) {
self.downloadProgress.completedUnitCount = [change[@"new"] longLongValue];
} else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesExpectedToReceive))]) {
self.downloadProgress.totalUnitCount = [change[@"new"] longLongValue];
} else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) {
self.uploadProgress.completedUnitCount = [change[@"new"] longLongValue];
} else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesExpectedToSend))]) {
self.uploadProgress.totalUnitCount = [change[@"new"] longLongValue];
}
}
else if ([object isEqual:self.downloadProgress]) {
if (self.downloadProgressBlock) {
self.downloadProgressBlock(object);
}
}
else if ([object isEqual:self.uploadProgress]) {
if (self.uploadProgressBlock) {
self.uploadProgressBlock(object);
}
}
}
在第一行判断object时,已经判断了是否是NSURLSessionTask,为什么还要判断或是否是NSURLSessionDownloadTask,NSURLSessionDownloadTask不是已经是NSURLSessionTask的子类了么?
NSURLSessionTask is actually a Class cluster. The task generated by NSURLSession does not necessarily return the specified task type. Therefore, kindOfClass does not always take effect. For details, please refer to the description of AFURLSessionManager.m in the load method.
Specific to the current problem, it is because the base class of __NSCFURLSessionDownloadTask on iOS 7 is not __NSCFURLSessionTask, so isKindOfClass will error. You can find out by looking at the corresponding commit.