gpt4 book ai didi

ios - AFNetworking 响应显示在日志中,但在调试器中为零

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:17:01 26 4
gpt4 key购买 nike

我正在使用 AFNetworking 获取 JSON 响应。我得到的是 PhotoPXArray(我使用 mantle 创建的模型)。日志输出正是我想要的数据。我的问题是使用数据。当我设置一个断点并查看 responseObject 时,它是零。我不知道为什么日志正在抽出数据,但调试器中的值为 nil。

我最终想做的是保存响应以备后用。

此外,我正在使用 Sculptor 来帮助进行序列化。

-(NSArray*) getPhotoForWord:(NSString*)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 serializerForModelClass:PhotoPXArray.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)getPhotoForWord:(NSString*)word completionHandler:(void (^)(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 serializerForModelClass:PhotoPXArray.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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com