我正在使用AFNetworking获取JSON响应。我得到的是PhotoPXArray(我使用地幔创建的模型)。日志输出正是我想要的数据。我的问题是使用数据。如何将响应数据保存为可在程序中其他位置使用的变量。
另外,我正在使用Sculptor来帮助序列化。
-(NSArray*) getPhotoForWord:(NSString*)word {
NSArray *results = 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, PhotoPXArray *responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
return results;
}
@end
答案 0 :(得分:0)
阅读有关blocks and variables的Apple文档。或者您可以在SO上查看此question,这可能也会回答您的问题。
来自Apple文档:
__块变量存在于变量的词法范围与声明的所有块和块副本之间共享的存储中 在变量的词法范围内创建。因此,存储将 如果块的任何副本,则在堆栈帧的破坏中存活 在框架内声明超出框架的末尾(for 例如,通过在某处加入队伍以便以后执行)。多 给定词法范围内的块可以同时使用共享 变量
答案 1 :(得分:0)
使用完成块来获取数据:
- (void)getPhotoForWord:(NSString *)word completionHandler:(void ^(PhotoPXArray *photoArray))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, PhotoPXArray *responseObject) {
NSLog(@"JSON: %@", responseObject);
if (completionHandler) {
completionHandler(responseObject);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}
然后这样称呼:
[object getPhotoForWord:@"word" completionHandler:^(PhotoPXArray *photoArray) {
// Do something with photo array.
}];
请注意,此调用是异步的,将在未来某个未知时间完成。此外,您可能会在完成块中使用NSError
参数,以便查看是否从请求中收到错误,但我会将其留给您。