iphone - 从网站订购多个异步 JSON 解析

标签 iphone objective-c ios

简要介绍一下我正在做的事情:我有两个数组,它们都包含 50% 的表格 View 信息。为什么?因为其中一个阵列从互联网上提取当前信息,而另一个阵列保存了用户数据。我不知道如何以一种不困惑的方式从互联网上获取当前信息,因为我是 Objective-C 的业余爱好者,更不用说在 Objective-C 中建立网络了。无论如何,因此互联网数组正在使用 AFNetworking 提取与已保存数组(保存在核心数据中)中的对象相对应的信息。因此它是我想要的异步的。现在问题来了,或者至少我可以从这种情况中得到什么。

我正在做一个 for 循环,它有效地计算保存数组中的对象并传递每个对象的唯一 ID,以便可以下载、解析来自 Internet 的相应信息并将其添加到 Internet 数组中。但是,由于网络是异步的,因此循环实际上是一次从 Internet 下载所有信息。因此,对象将按照先下载的顺序写入互联网阵列。因此 savedArray[0] 不对应于 internetArray[0] 中的对象。正如您可以想象的那样,这是一个很大的缺陷,因为当我将值插入到我的 tableView 中时,没有什么真正匹配/有意义。

我真的在寻找一种方法来推迟信息的下载,直到之前的下载完成并添加到 internetArray,我到底该怎么做?现在是代码。这是我获得适当 key 的地方:

for ( int i = 0; i < [mySavedObjects count]; i++) {
    MySavedObject* mySavedObject = [mySavedObjects objectAtIndex:i];
    [self retrieveMissingInformation: myObject.Id];
    [self.tableView reloadData];
}

这是我实际获取信息的地方(为了空间而简化):
- (void)retrieveMissingInformation:(NSString *) Id
{
 // create URL here.
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
              success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
                        NSLog(@"Success");
                        // Do some safety checks & parse the JSON, returning a searchResult.
                        [searchResults addObject:searchResult];
            } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)
                        // Do some error messages etc.
}];

[queue addOperation:operation]; //where queue is an ivar NSOperationQueue.
}

最后,在 cellForRowAtIndexpath 中,我使用了这两个:
MySavedObject *mySavedObject = [mySavedObjects objectAtIndex:indexPath.row];

&
SearchResult *searchResult = [searchResults objectAtIndex:indexPath.row];

获取单元格的值。

对不起,巨大的文字墙。我真的不够好,无法有效地解释事情,经常在术语上结结巴巴,不得不求助于自己的例子。订购这个烂摊子的任何帮助,我将不胜感激。

问候,
麦克风。

最佳答案

好的工作伙伴,你偶然发现了一个常见的设计模式。

正如您所看到的,对于异步请求,执行几乎同时发生,因此当您从 for 循环的角度考虑“队列”时,您无法保证顺序。

您需要考虑下载队列的方式是递归。

换句话说,而不是:

// your current method of queue-ing the submission of data
for(int i = 0; i < arrData.count; i++)
{
    [self doAsyncDataSendForIndex:i];
}

你需要开始做这样的事情:
// perform the first submit for the first element in your array
[self doAsyncDataSendForIndex:dataIndex];


// a completion callback method
-(void)asyncFinishDownloading
{
    [self parseResult:serverReturnedData];
}

-(void)parseResult:(id)serverData
{
    // do all the processing of the data that you need here

    ...

    // update index for next round
    dataIndex++;

    // -----------------------------------------------------------------
    // now at the end of this method, perform a recursive call 
    // of your async download method again 
    // -----------------------------------------------------------------
    [self doAsyncDataSendForIndex:dataIndex];
}

使用对下载进行排队的回调委托(delegate)方式,您是在告诉代码仅在处理完最后一次异步下载后才下载下一个数据。

现在,您可以使用许多库来帮助您处理异步内容。我自己使用 ASIHttpRequest 和 ASIFormData,你也可以使用更新的 AFNetworking。
-(void)asyncSubmitData:(id)someData
{
    NSURL *url = [NSURL urlWithString:@"http://www.yourserver.com/...."];

    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

    // setup your POST request parameters
    [request setPostValue:someData forKey:@"someKey"];
    ...

    // setup the completion callback delegate action
    [request setCompletionBlock:^{
        // process your server returned data here
        NSString *serverResponse = [request responseString]; // raw server response

        ...

        // increment your index and call your download method again
        dataIndex++;

        [self asyncSubmitData:[myArray objectAtIndex:dataIndex]];
    }];


    // setup fail block in case the server fails
    [request setFailedBlock:^{
        NSLog(@"Server error: %@", [[request error] localizedDescription];
    }];


    // start the asynchronous request now
    [request startAsynchronous];
}

希望有帮助。

关于iphone - 从网站订购多个异步 JSON 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13635963/

相关文章:

iphone - 在 Safari 中打开 URL 而不是 webView

iphone - 没有边框的圆角矩形 UIButton

iphone - 在 Objective C 中创建链表

ios - 如何在 Objective-C 项目中遵循 Swift 库中制定的协议(protocol)

ios - 如何根据屏幕和网页分辨率调整 webView 的大小?

ios - 通过蓝牙 3.0 在 iOS 应用程序和非 ios 设备之间传输文件

iphone - NSFetchedResultsController 的部分名称与托管对象值不匹配

iphone - 将 VOID 代码转换为 IBAction

iphone - 如何正确设计多方向 iPad 应用程序

ios - 诊断不可重现的错误?