我正在使用 AFNetworking 来获取 JSON 响应。我得到的是一个 PhotoPXArray(我使用地幔创建的模型)。日志输出正是我想要的数据。我的问题是使用数据。当我设置一个断点并查看 responseObject 时,它是 nil。我不知道为什么日志会抽出数据,但调试器中的值是 nil。
我最终要做的是保存响应以供以后使用。
另外,我正在使用 Sculptor 来帮助进行序列化。
-(NSArray*) getPhotoForWordNSString*)word {
NSArray *results = nil;
__block NSMutableDictionary *test = nil;
NSString *requestString = BASE_URL;
requestString = [requestString stringByAppendingString"photos/search?term="];
requestString = [requestString stringByAppendingString:word];
requestString = [requestString stringByAppendingString:CONSUMER_KEY];
NSString *encoded = [requestString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [SCLMantleResponseSerializer serializerForModelClasshotoPXArray.class];
[manager GET:encoded
parameters:nil
//success:^(AFHTTPRequestOperation *operation, id responseObject) {
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
test = responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
return results;
}
你从不设置 results
变量,所以当然会返回 nil
。即使您使用了 test
(您确实设置了),这也是异步发生的,所以当您立即返回时,它也将是 nil
,只获得 responseObject
稍后值。
您可以考虑采用异步模式,而是提供一个完成处理程序参数:
- (void)getPhotoForWordNSString*)word completionHandlervoid (^)(id responseObject, NSError *error))completionHandler{
NSString *requestString = BASE_URL;
requestString = [requestString stringByAppendingString"photos/search?term="];
requestString = [requestString stringByAppendingString:word];
requestString = [requestString stringByAppendingString:CONSUMER_KEY];
NSString *encoded = [requestString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [SCLMantleResponseSerializer serializerForModelClasshotoPXArray.class];
[manager GET:encoded parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (completionHandler) {
completionHandler(responseObject, nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (completionHandler) {
completionHandler(nil, error);
}
}];
}
然后你会这样调用它:
[obj getPhotoForWord:word completionHandler:^(id responseObject, NSError *error) {
// use responseObject here
}];
// do not use it here because the above happens asynchronously (i.e. later)
关于ios - AFNetworking 响应显示在日志中,但在调试器中为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29050446/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |