在每个循环中,我使用用于执行JSON调用的id初始化连接器类。问题是,这个循环在连接器类的connectionDidFinishLoading委托方法完成之前继续迭代,根据需要解析JSON,然后使用委托方法和它检索的信息。
for(NSDictionary *item in views){
NSInteger myID = [[item valueForKey:@"id"] integerValue];
//filter contains these two dictionaries
NSDictionary *ownerDictionary = [filterDictionary valueForKey:@"owner"];
NSString *ownerDisplayName = [ownerDictionary valueForKey:@"displayName"];
self.projectName = projectName;
self.ownerName = ownerDisplayName;
//value inside dictionary for owner
NSString *ownerDisplayName = [ownerDictionary valueForKey:@"displayName"];
//I initialize the connector class here
self.sprintConnector = [[SprintConnector alloc] initWithId:myID];
[self.sprintConnector setDelegate:self];
//**I do not want to continue this loop until the delegate method that i implement is called**/
}
//implementation of delegate method
-(void)didFinishLoadingStuff:(MyObject *)obj{
Project *newProject = [[Project alloc] init];
newProject.projectName = self.projectName;
newProject.projectOwner = self.ownerName;
newProject.sprint = sprint;
//Ok now i have the information that i need, lets continue our loop above
}
//设置请求的连接器类的方法如下:
-(void)retrieveSprintInfoWithId{
NSURLConnection *conn;
NSString *urlString = @"myJSONURL";
NSURL *url = [NSURL URLWithString:[urlString stringByAppendingString:self.ID]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(@"data coming from request: %@", data );
[self.data appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"we finished loading");
NSError *error = nil;
self.projectsDict = [[NSDictionary alloc] initWithDictionary:[NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingMutableContainers error:&error]];
NSLog(@"Our sprint array with id: %@ %@", self.ID, self.projectsDict);
//this is where we parse the JSON then use the delegate method that the above class will implement
[self parseJSON];
}
-(void)parseJSON{
[self.delegate didFinishLoadingStuff:SomeObject];
}
我希望能够强制调用connectionDidFinishLoading方法 - > parseJSON->委托方法,并在循环继续之前完成上述方法的实现。
我有什么选择?最佳做法?等等?
答案 0 :(得分:2)
你要做的是同步发出请求,我会告诉你如何做,但你不应该这样做,所以在我向你展示如何发出同步请求后,我会告诉你应该如何处理此
1-要同步发出请求,您可以使用NSURLConnection的sendSynchronousRequest
方法,这将阻止直到收到数据并返回数据,这里是docs。你不应该这样做,因为你可能会阻止主线程,这会导致糟糕的用户体验(也是为什么这是不好的做法的其他原因)
2-您应该像在示例代码中那样发出请求异步,在回调中,您应该获取相应的对象(您应该通过项目ID知道),然后执行您需要执行的任何操作对于那个对象...如果你需要加载所有东西以便进行某些操作,那么你应该跟踪它(发送请求与收到的响应)
希望有所帮助
丹尼尔