0

大家好,我玩了ASIHttpRequestAFNetworking有一段时间了,今天尝试更深入地阅读AFNetworking的源码,它确实是一个功能强大且设计精良的网络框架,现在我有几个问题要问: 1 AFJSONRequestOperation、:

NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:kMobileBind parameters:paramsBase];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {  //successblock   } fail:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON){  //failblock   }

在此之后,创建的操作和成功块和失败块被设置为它,然后我们开始操作,它NSURLconnection在单例线程中启动,

[self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]];

里面 operationDidStart:</p>

 [self.lock lock];
 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    for (NSString *runLoopMode in self.runLoopModes) {
        [self.connection scheduleInRunLoop:runLoop forMode:runLoopMode];
        [self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode];
    }
[self.connection start];
[self.lock unlock];

此操作运行并NSURLconnection调用回调,

 - (void)connectionDidFinishLoading:(NSURLConnection *)__unused connection {
self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
[self.outputStream close];
[self finish];
self.connection = nil;
}

- (void)finish {
    self.state = AFHTTPOperationFinishedState;
}

finish方法设置操作状态,它使用KVO技术,完成操作:我没有看到observeValueForKeyPath和[obj addObserver:self forKeyPath:@"isFinished" options:0 context:NULL];KVO 是如何工作的?

设置状态:

    [self willChangeValueForKey:newStateKey];
    [self willChangeValueForKey:oldStateKey];
    _state = state;
    [self didChangeValueForKey:oldStateKey];
    [self didChangeValueForKey:newStateKey];



- (BOOL)isFinished {
    return self.state == AFHTTPOperationFinishedState;
}

然后我被困在这里,我找到了 setcallblock 基金,但无法理解 self.completionBlock 是如何被调用的:

- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

   failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure

{
    self.completionBlock = ^ {
    if ([self isCancelled]) {
        return;
    }

    if (self.error) {
        if (failure) {
            dispatch_async(self.failureCallbackQueue ? self.failureCallbackQueue : dispatch_get_main_queue(), ^{
                failure(self, self.error);
            });
        }
    } else {
        if (success) {
            dispatch_async(self.successCallbackQueue ? self.successCallbackQueue : dispatch_get_main_queue(), ^{
                success(self, self.responseData);
            });
        }
    }
};

}

可能是我仔细阅读了代码,但这真的让我很困惑,任何有 AFNetworking 经验的人请解释这个框架,

还有一个问题,网络请求在共享线程上运行,会减慢请求吗?

我确实想提高我在多线程编程方面的技能,我需要示例和建议,我已经阅读了苹果的文档,并做了一些简单的演示,还没有尝试过一个大项目或编写一个健壮的框架或模型,我该如何开始? 非常感谢

4

1 回答 1

1

completionBlockAFJSONRequestOperation超类的属性,NSOperation. 它在操作完成时执行。

于 2013-12-03T16:43:30.657 回答