2016-08-02 46 views
0

我使用這種方法在我的圖像上顯示圖像,但是當它進入調度方法時,索引正在增加。 意味着當我是1它設置爲2. 請讓我知道什麼問題。爲什麼我的for循環的索引在使用grand dispatch時增加

謝謝。

for var i = 0 ; i<featuredCards.count ; i++ { 

    print("INDEXxxxxxxxxxxxx",i) 
    if i >= self.cardFeatruedTitlesCollection.count { 
     break 
    } 

    if photoModel.photoURL == featuredCards[i].cardPreviewImages[safe:0]?.photoURL { 

     dispatch_async(dispatch_get_main_queue(), {() -> Void in 

     if let path = photoModel.photoPath { 

      if let image : UIImage = photoModel.getThumbnailPhotoWithPath(path) { 

       if let imageView = self.cardFeaturedImagesCollection[safe:i] { 
        imageView.image = image 
       } 

      } 
     } 
     }) 
    } 
} 
+1

你已經有相當的厄運金字塔在那裏。你應該閱讀'guard'語句和多個'如果let'綁定語句 – Alexander

回答

3

您在循環這不是一個好主意,因爲調度塊循環迭代這就是爲什麼它是越來越增加值完成後,將執行訪問主隊列。

試試這個

dispatch_async(dispatch_get_main_queue()) { 

    for var i = 0 ; i<featuredCards.count ; i++ { 

     print("INDEXxxxxxxxxxxxx",i) 
     if i >= self.cardFeatruedTitlesCollection.count { 
      break 
     } 

     if photoModel.photoURL == featuredCards[i].cardPreviewImages[safe:0]?.photoURL { 


      if let path = photoModel.photoPath { 

       if let image : UIImage = photoModel.getThumbnailPhotoWithPath(path) { 

        if let imageView = self.cardFeaturedImagesCollection[safe:i] { 
         imageView.image = image 
        } 

       } 
      } 
     } 
    } 
} 

編輯:

您可以通過兩種方式

  1. 使用__block變量
  2. 將您的mainqueue塊像下面內環解決問題:如果您使用的是swift 3,那麼您應該使用以下語法:

    DispatchQueue.main.async { 
        //Your For Loop 
    } 
    
+0

非常感謝你:) –

+0

我應該爲變量i添加__嗎? –

+0

使用__block變量是選項,但不是一個好主意 –

0

當你排隊工作塊到主隊列使用dispatch_async,控制權會立即返回調用點(這裏,環路),然後你排隊的執行工作前進行和增量i(並讀取您期望的值i)。

var i : Int的值是循環和您正在調度的代碼的閉包之間的共享狀態。這導致競爭條件:在排隊工作讀取i之前,循環可能會修改i

您可以在循環中使用恆定副本i以減少共享狀態的數量。

let photoIndex = i 

dispatch_async(dispatch_get_main_queue(), {() -> Void in 
if let path = photoModel.photoPath { 
    if let image : UIImage = photoModel.getThumbnailPhotoWithPath(path) { 
     if let imageView = self.cardFeaturedImagesCollection[safe: photoIndex] { 
      imageView.image = image 
     } 

    } 
} 
相關問題