假设我有3个异步方法,它们都做同样的事情:将一些数据发送到服务器并将响应数据添加到数组(所有这些方法都添加到相同的阵列)。确保异步方法按照它们被调用的顺序执行
我在同一时间调用这些方法,但他们发送不同数量的数据到服务器。
如果第一个方法比第三个方法向服务器发送更多的数据,第三个方法将尽快返回响应,从而更快地将数据添加到数组中。响应数据取决于坐标,所以它们在数组中的顺序很重要。
我该如何确定,即使第三个方法比第一个或第二个方法获得repsonse更快,在前面的方法之前它不会将数据添加到数组中?因此,保持数组中坐标的顺序。
方法是NSURLConnection
s,它们都发送异步请求。
编辑:这里是工作代码:
//Array of snapped points from the JSON
NSArray *snappedPoints = [result objectForKey:@"snappedPoints"];
NSMutableArray *locationsArray = [[NSMutableArray alloc] init];
//Loop through the snapped points array and add each coordinate to a temporary array
for (int i = 0; i<[snappedPoints count]; i++) {
NSDictionary *location = [[snappedPoints objectAtIndex:i] objectForKey:@"location"];
double latitude = [[location objectForKey:@"latitude"] doubleValue];
double longitude = [[location objectForKey:@"longitude"] doubleValue];
CLLocation *loc = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
[locationsArray addObject:loc];
}
//Add these temporary location arrays to the dictionary with the key as the request number
[tempLocationDictionary setObject:locationsArray forKey:[NSString stringWithFormat:@"%i",requestNumber]];
//If all requests have completed get the location arrays from the dicitonary in the same order as the request were made
if([tempLocationDictionary count] == numberOfRequests){
//Just a path because I am drawing these coordinates on a map later
GMSMutablePath *path = [GMSMutablePath path];
//Loop through the dictionary and get the location arrays in the right order
for (int i = 0; i<[tempLocationDictionary count]; i++) {
//Create a dummy array
NSArray *array = [tempLocationDictionary objectForKey:[NSString stringWithFormat:@"%i",i+1]];
//Get the coordinates from the array which we just got from the dictionary
for (CLLocation *location in array) {
[path addCoordinate:location.coordinate];
}
}
取决于这些方法正在做什么使它们异步。这些'NSURLSession'调用? 'NSOperationQueue'?还有别的吗? –
NSURLConnection与异步请求! –
用相关的代码更新你的问题,这样人们就可以指引你一个好的方向。 – rmaddy