2014-11-08 65 views
0

我在當前項目中遇到問題。管理對象屬性上的EXC_BAD_ACCESS

目標是下載PDF文件並將其顯示在UIPageViewController中。 用戶可以通過NSFetchedResultsController提供的UICollectionView滾動瀏覽可用的pdf。

如果讀取按鈕被觸發,被管理對象被傳遞給ViewController, 檢查是否已經下載了PDF或是否需要下載並顯示它。

此代碼負責加載新的視圖控制器並將管理對象傳遞給它。

- (IBAction)readNowButtonPressed:(UIButton *)sender 
{ 

    UICollectionViewCell *cell = (UICollectionViewCell*)[[sender superview] superview]; 
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:cell.tag inSection:0]; 
    EPaper *epaper = [self.fetchedResultsController objectAtIndexPath:indexPath]; 

    if (epaper) { 

     DHEPaperLoadingViewController *epaperLoadingViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"epaperLoadingController"]; 
     epaperLoadingViewController.epaper = epaper; 
     epaperLoadingViewController.hidesBottomBarWhenPushed = YES; 
     [self.navigationController pushViewController:epaperLoadingViewController animated:YES]; 
    } 

} 

此代碼位於新View Controller的viewDidLoad方法中,並決定如何處理數據。

if (self.epaper.pdfData) { 
     [self createPDFForData:self.epaper.pdfData]; 
     [self displayPDF]; 
    } 
    else { 
     [DHDownloadHelper downloadPDFWithRequest:[self createURLRequest]]; 

     __weak DHEPaperLoadingViewController *weakSelf = self; 
     EPaper *currentEpaper = self.epaper; 
     [[NSNotificationCenter defaultCenter] addObserverForName:EPAPER_DOWNLOAD_PROGRESS_NOTIFICATION object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) { 
      NSDictionary *userInfo = note.object; 
      float progress = [[userInfo objectForKey:EPAPER_DOWNLOAD_PROGRESS] floatValue]; 
      weakSelf.progressBar.progress = progress; 
     }]; 

     [[NSNotificationCenter defaultCenter] addObserverForName:EPAPER_DOWNLOAD_FINISHED_NOTIFICATION object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) { 
      NSDictionary *userInfo = note.object; 
      NSData *data = [userInfo objectForKey:EPAPER_DOWNLOAD_DATA]; 
      currentEpaper.pdfData = data; 


      [currentEpaper.managedObjectContext save:nil]; 
      [weakSelf createPDFForData:data]; 
      [weakSelf displayPDF]; 
     }]; 
    } 
} 

這在大多數情況下工作正常。但是那裏有EXC_BAD_ACCESS出現在這條線要發生的情況:

if (self.epaper.pdfData) //EXC_BAD_ACCESS 

以下情況下會出現此錯誤,可以被複制:

  • 讀按鈕被觸發同樣項目的3倍(它可以被觸發一次,並正確下載,它可以再次被觸發 ,它正確顯示PDF而不再下載它,但 它第三次崩潰)
  • 一個pdf被下載並顯示正確,另一個項目需要 要下載

據我所知EXC_BAD_ACCESS發生時,對象已經釋放,但 我有一個強大的指針,並檢查它是否響應屬性選擇器(這是做)。我也確保代碼在主線程上執行。

還有什麼可能導致此問題?

預先感謝您。

回答

0

你可以試試這個

if (self.epaper && self.epaper.pdfData) 

,但我不知道是否會被隱藏的另一個問題。

你是否正在移除自己作爲這些通知的觀察者?來自文檔...

您必須在釋放由addObserverForName:object:queue:usingBlock:指定的任何對象之前調用removeObserver:或removeObserver:name:object:。

+0

感謝您的回覆。 self.epaper不是零。它實際上持有對管理對象的引用,就像它應該的那樣。 當我嘗試訪問self.epaper.pdfData時,代碼通過if(self.epaper)條件但崩潰(在上述情況下)。 我忘了刪除自己,但現在添加它。仍然導致相同的錯誤。但是,感謝啓蒙! – 2014-11-08 16:36:49