我想从服务器中获取带有多个内部for循环调用的数据。我每次都传递不同的参数。我知道可以获取数据,比如我在下面的代码中获取数据:
for (NSDictionary *feedItem in [feed objectForKey:@"content"]) {
// url with feedItem data.
NSURL *url = ....
[UrlMethod GetURL:url success:^(NSDictionary *placeData) {
if (placeData) {
dispatch_async(dispatch_get_main_queue(), ^{
// adding object to table data source array
[dataSourceArray addObject:[placeData objectForKey:@"data"]];
// reloading table view.
[self.tableView reloadData];
});
}
} failure:^(NSError *error) {
}];
}
问题是,每当我向dataSourceArry添加数据时,它都不是按顺序添加的。它是根据API调用的响应添加的。如果不清楚,请告诉我。
答案 0 :(得分:1)
这对你有帮助,
//keep dictionary property which will store responses
NSMutableDictionary *storeResponses = [[NSMutableDictionary alloc]init];
//Somewhere outside function keep count or for loop
NSInteger count = 0;
for (NSDictionary *feedItem in [feed objectForKey:@"content"]) {
//Find out index of feddItem
NSInteger indexOfFeedItem = [[feed objectForKey:@"content"] indexOfObject:feedItem];
NSString *keyToStoreResponse = [NSString stringWithFormat:@"%d",indexOfFeedItem];
// url with feedItem data.
NSURL *url = ....
[UrlMethod GetURL:url success:^(NSDictionary *placeData) {
if (placeData) {
//instead of storing directly to array like below
// adding object to table data source array
[dataSourceArray addObject:[placeData objectForKey:@"data"]];
//follow this
//increase count
count++;
[storeResponses setObject:[placeData objectForKey:@"data"] forKey:keyToStoreResponse];
// reloading table view.
if(count == [feed objectForKey:@"content"].count)
{
NSMutableArray *keys = [[storeResponses allKeys] mutableCopy]; //or AllKeys
//sort this array using sort descriptor
//after sorting "keys"
for (NSString *key in keys)
{
//add them serially
[dataSourceArray addObject:[storeResponses objectForKey:key]];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
}
} failure:^(NSError *error) {
}];
}
编辑:我给出的答案直接写在这里,在实际运行此代码时可能会遇到编译错误
答案 1 :(得分:0)
这是因为您要异步调用网络服务,所以它不能保证它会按照您的要求按顺序给出响应!
现在的解决方案:
api
,就像它一次提供所有数据一样。所以,
您不需要进行多次网络呼叫,它会得到改善
表现也是!completion handler
发出另一个请求。在这种情况下,一旦你得到响应,那么只有另一个请求将被初始化,但在这种情况下你将不得不妥协性能!所以根据我的第一个解决方案更好!tableView
答案 2 :(得分:0)
请尝试以下方法: -
for (NSDictionary *feedItem in [feed objectForKey:@"content"]) {
// url with feedItem data.
NSURL *url = ....
[UrlMethod GetURL:url success:^(NSDictionary *placeData) {
if (placeData) {
// adding object to table data source array
[dataSourceArray addObject:[placeData objectForKey:@"data"]];
// reloading table view.
dispatch_sync(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});
} failure:^(NSError *error) {
}];
}
答案 3 :(得分:0)
每次循环时都不要重新加载表。循环完成获取数据后,对datasourcearray进行排序以获得所需的结果,然后重新加载表。