这可能是一个幼稚的问题,但是在我加载ViewController时,我使用一组下面的getEachItem之类的方法来加载应用程序所需的所有内容。通常这就像2或3个项目,它们都被写入缓存。
我想调用getEachItem的最终实例完成后运行的方法“showNavigation”,但不确定如何执行此操作。 getEachItem通过AFNetworking进行GET请求。类似于jQuery完整块,但下面的for循环是完整的。

NSArray *tmpItems=[result objectForKey:@"ipad_items"];
for(NSDictionary *m in tmpItems){
  // will also increment into the _menus array
  [self getEachItem:[m objectForKey:@"id"]];
  [self getImages:[m objectForKey:@"id"]];
}
[self showNavigation];

最佳答案

当您调用AFNetworking GET方法时,它将返回AFHTTPRequestOperation(一个NSOperation子类)。您可以利用这一事实为您的问题采用基于操作队列的解决方案。即,您可以创建一个新的“完成操作”,该操作取决于特定的AFNetworking操作的完成。

例如,您可以更改getEachItem方法以返回AFHTTPRequestOperation方法返回的GET。例如,假设您当前已定义了一个getEachItem,例如:

- (void)getEachItem:(id)identifier
{
     // do a lot of stuff

     [self.manager GET:... parameters:... success:... failure:...];
}

更改为:
- (NSOperation *)getEachItem:(id)identifier
{
    // do a lot of stuff

    return [self.manager GET:... parameters:... success:... failure:...];
}

然后,您可以创建自己的完成操作,该操作将取决于所有其他AFHTTPRequestOperation操作的完成。从而:
NSOperation *completion = [NSBlockOperation blockOperationWithBlock:^{
    [self showNavigation];
}];

NSArray *tmpItems=[result objectForKey:@"ipad_items"];
for(NSDictionary *m in tmpItems){
    // will also increment into the _menus array
    NSOperation *operation = [self getEachItem:[m objectForKey:@"id"]];
    [completion addDependency:operation];
    [self getImages:[m objectForKey:@"id"]];
}

[[NSOperationQueue mainQueue] addOperation:completion];

完成此操作后,直到所有completion操作完成后,才会触发getEachItem操作。请注意,当核心AFHTTPRequestOperation对象完成时,将触发此完成操作,但不能保证必须完成这些请求各自的完成块。

另一种方法是使用GCD“组”。使用这种技术,您可以在提交每个请求时“输入”组,然后将组“保留”在GET方法的完成块中。然后,当组通知您离开组的次数与您输入组的次数相同时,您可以指定要执行的代码块(即,所有AFNetworking网络请求及其success / failure块均已完成) )。

例如,在dispatch_group_t中添加一个getEachItem参数:
- (void)getEachItem:(id)identifier group:(dispatch_group_t)group
{
    dispatch_group_enter(group);

    // do a lot of stuff

    [self.manager GET:... parameters:... success:^(...) {
        // do you success stuff and when done, leave the group

        dispatch_group_leave(group);
    } failure:^(...) {
        // do you failure stuff and when done, leave the group

        dispatch_group_leave(group);
    }];
}

注意,您在提交请求之前先“输入”该组,并且successfailure块都必须调用dispatch_group_leave

完成此操作后,您现在可以在请求循环中使用dispatch_group_t,并在群组收到其所有操作已完成的通知时执行showNavigation:
dispatch_group_t group = dispatch_group_create();

NSArray *tmpItems=[result objectForKey:@"ipad_items"];
for(NSDictionary *m in tmpItems){
    // will also increment into the _menus array
    [self getEachItem:[m objectForKey:@"id"] group:group];
    [self getImages:[m objectForKey:@"id"]];
}

dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    [self showNavigation];
});

关于ios - 在一组其他方法执行完后,是否可以在Objective-C中调用方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25465939/

10-12 14:45
查看更多