2012-09-18 133 views
0

我有以下代碼:問題與NSOperationQueue,weakSelf和塊

[[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。所以這是一個依賴項,我應該如何添加這個依賴項?

更新:

這裏的崩潰日誌,如果有幫助:

enter image description here

回答

1

建議「放鬆」塊弱引用,那麼請試試這個:

__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); 
}]; 
+3

誰建議你這樣做,他們給了什麼理由? – kubi

+0

可可開發人員推薦這個,但我沒有在這裏提供的URL。在多線程環境中,一個星期的引用可能在塊的中間變成'nil'。但是,當你將它解引入強壯的對象時,則該對象將保證存在直到該塊的結尾。 – Stream

+1

是的,但哪些可可開發商?你所做的至少一些強壯的自我,虛弱的自我體操是不必要的,因爲對nil的調用方法什麼都不做。 – kubi