【发布时间】:2015-02-19 17:46:12
【问题描述】:
我有以下要求:
鉴于分层树状结构,我正在执行breadth-first-search 遍历整个数据集。数据由 API 提供,方法如下:(使用 AFNetworking 向服务器发出请求,将结果保存到 Core Data 并在成功时使用存储的条目回调完成块)
-(void) getChildrenForNodeId:(NSNumber*)nodeId
completion:(void (^)(NSArray *nodes))completionBlock;
控制器执行获取数据的方法:
-(void)getAllNodesWithCompletion:(void (^)(NSArray *nodes))completionBlock{
NSNumber *rootId = ...
[MyNetworkManager getChildrenForNodeId:rootId completion:^(NSArray *nodes){
for(Node *node in nodes){
[self iterateOverNode:node.nodeId];
}
//execute completionBlock with nodes fetched from database that contain all their children until the very last leaf
}];
}
问题来了:
-(void)iterateOverNode:(NSNumber*)nodeId {
NSMutableArray *elements = [NSMutableArray array];
[elements addObject:nodeId];
while ([elements count]) {
NSNumber *current = [elements objectAtIndex:0];
[MyNetworkManager getChildrenForNodeWithId:current completion:^(NSArray *nodes) {
/**
In order to continue with the loop the elements array must be updated. This can only happen once we have retrieved the children of the current node.
However since this is in a loop, all of these requests will be sent off at the same time, thus unable to properly keep looping.
*/
for(Node *node in nodes){
[elements addObject:node.nodeId];
}
[elements removeObjectAtIndex:0];
}];
}
}
基本上我需要回调的结果来控制while循环的流程,但我不知道如何实现它。我的理解是,从while-loop 中对getChildrenForNodeWithId:completion: 的请求应该以串行顺序在一个新线程中发生,以便在第一个线程完成后开始另一个线程。我不确定如何使用 NSOperation 或 GCD 来实现这一点。任何帮助将不胜感激。
【问题讨论】:
-
那么您是在问如何下载所有节点并将它们保存到核心数据中,因为每个节点都可能包含其他节点?
-
没错。我理解这个问题,我不知道如何使用异步 Web 服务请求来解决这个问题。
-
MyNetworkManager 的实现是什么?
-
AFHTTPRequestOperationManager 的子类,它调用给定信息的 API。检索数据时,会将其保存到核心数据中。保存完成后,执行完成块。
-
我的解决方案有帮助吗?
标签: ios asynchronous while-loop objective-c-blocks breadth-first-search