【问题标题】:AFNetworking + AFHTTPRequestOperation not being able to save ArrayAFNetworking + AFHTTPRequestOperation 无法保存数组
【发布时间】:2015-03-27 19:44:57
【问题描述】:

所以我试图在线访问一个 json 文件,当我使用 AFHTTPRequestOperation 方法运行完成块时,我可以获取 JSON 文件的内容。但是当我尝试在完成块之外进行 NSLog 时,它变为空。我想知道为什么会发生这种情况以及我将如何解决这个问题。以下是我到目前为止的代码:

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCredential:credentials];
    [operation setResponseSerializer:[AFJSONResponseSerializer alloc]];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Success %@", responseObject);
        jsonOutputData = [NSMutableArray arrayWithObject:responseObject];
        self.newsFeedArray = [NSMutableArray arrayWithArray:[jsonOutputData copy]];


    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
        NSLog(@"Failure: %@", error);
    }];

    [manager.operationQueue addOperation:operation];
    NSLog(@"%@", self.newsFeedArray);

带有 Success 的 NSLog 显示 JSON,但带有 self.newsFeedArray 的 NSLog 显示 (null)。我只是想知道为什么会这样。如果您需要更多说明,请告诉我。任何帮助,将不胜感激!

谢谢!

【问题讨论】:

    标签: ios objective-c json xcode afnetworking-2


    【解决方案1】:

    成功和失败块被异步调用。所以self.newsFeedArray在最后一次NSLog调用的时候还没有设置,因为操作还没有完成。

    您可以等待操作完成(例如,[operation waitUntilFinished]),但您几乎肯定不想这样做,尤其是在主线程上。而是让完成块触发所需的行为。

    【讨论】:

    • 将 AFHTTP 部分放在 viewWillAppear 中是否可以,并将最后一个“NSLog”保留在 viewDidLoad 中?
    • @hparmar 视图独立于网络操作。即使您找到将代码放在大部分时间对您有用的地方,如果网络速度较慢等情况下,它也可能会失败。您可以同时显示一个加载指示器,并且只有在数据可用时才用数据填充视图(从成功块调用方法来执行此操作)。还请记住,操作可能会因您无法控制的各种原因而失败(调用失败块)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-28
    • 1970-01-01
    相关资源
    最近更新 更多