繁体   English   中英

NSOperationQueue,weakSelf和block的问题

[英]issue with NSOperationQueue, weakSelf and blocks

我有以下代码:

 [[AHPinterestAPIClient sharedClient] getPath:requestURLPath parameters:nil 
             success:^(AFHTTPRequestOperation *operation, id response) {


                 [weakSelf.backgroundQueue_ addOperationWithBlock:^{
                     [self doSomeHeavyComputation];                    


                     [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                           [weakSelf.collectionView_ setContentOffset:CGPointMake(0, 0)];
                     [weakSelf.collectionView_ reloadData];
                     [weakSelf.progressHUD_ hide:YES];
                     [[NSNotificationCenter defaultCenter] performSelector:@selector(postNotificationName:object:) withObject:@"UIScrollViewDidStopScrolling" afterDelay:0.3];
                     [weakSelf.progressHUD_ hide:YES];


                      }];

                  }];

             }
             failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [weakSelf.progressHUD_ hide:YES];
                [weakSelf.collectionView_.pullToRefreshView stopAnimating];
                 NSLog(@"Error fetching user data!");
                 NSLog(@"%@", error);
             }];

出于某种原因,这在iOS 5中可以正常工作,但在iOS 6中则无法工作(崩溃)。 现在,我不再要问有关iOS 6的问题,因为它仍处于NDA之下。 我想知道的是,以上代码是否错误? 如果是,我该如何解决。

如果我将代码放在mainQueue之外的块中,那就很好。 我要在这里做的是仅在[self doSomeHeavyComputation]完成后再执行NSOperationQueue mainQueue。 所以这是一个依赖关系,我应该如何添加这个依赖关系?

更新:

如果有帮助,请查看崩溃日志:

在此处输入图片说明

建议在区块中“展开”弱引用,因此请尝试以下操作:

__weak id weakSelf = self;
[client getPath:path parameters:nil success:^(id op, id response) {
    id strongSelf = weakSelf;
    if (strongSelf == nil) return;

    __weak id internalWeakSelf = strongSelf;
    [strongSelf.backgroundQueue_ addOperationWithBlock:^{
        id internalStrongSelf = internalWeakSelf;
        if (internalStrongSelf == nil) return;

        [internalStrongSelf doSomeHeavyComputation];                    

        __weak id internalInternalWeakSelf = internalStrongSelf;
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            id internalInternalStrongSelf = internalInternalWeakSelf;
            if (internalInternalStrongSelf == nil) return;

            [internalInternalStrongSelf reloadCollectionView];
        }];
    }];
}
failure:^(id op, NSError *error) {
    id strongSelf = weakSelf;
    if (strongSelf == nil) return;

    [strongSelf stopProgress];
    NSLog(@"Error fetching user data: %@", error);
}];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM