2015-10-21 37 views
0

在viewWillAppear方法中使用scrollToRowAtIndexPath時,出現EXC_BAD_ACCESS錯誤。我搜索瞭解決方案,並看到一些舊帖子建議將委託和表設置爲零(請參閱下面的代碼),但是當我設置時,我根本沒有在我的tableview中加載任何東西。 我應該說這是聊天應用程序的一部分,我希望顯示最先輸入的最後一條消息。非常感謝您的幫助。 這裏是我的viewWillAppear中:EXC_BAD_ACCESS使用scrollToRowAtIndexPath的viewwillappear錯誤

-(void)viewWillAppear:(BOOL)animated { 
    [self.table reloadData]; 
    int lastRowNumber = [self.table numberOfRowsInSection:0] - 1; 
    NSIndexPath* ip = [NSIndexPath indexPathForRow:lastRowNumber inSection:0]; 
    //self.table.delegate = nil; 
    //self.table = nil; 
    [self.table scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionTop animated:YES]; 

} 

我要補充,該代碼似乎工作在我的計劃,我唯一一次得到的錯誤是在viewWillAppear中方法的其他部分罰款。

+0

表是不是零? – Aggressor

+0

http://stackoverflow.com/a/2696909/3324388 – Aggressor

+0

嘗試將動畫設置爲NO。 –

回答

0

它可以幫助你

NSIndexPath * lastIndex =[NSIndexPath indexPathForRow:yourContenetArray.count-1 inSection:0]; 

[self.yourTableView scrollToRowAtIndexPath:lastIndex atScrollPosition:UITableViewScrollPositionNone animated:YES]; 
+0

嗨,謝謝,但我仍然得到相同的EXC_BAD_ACCESS錯誤。實際上,這段代碼在我的程序的其他部分工作,錯誤只發生在viewWillAppear。 – Kitcc

2

viewWillAppear:太早做視圖的任何動畫。每Apple Documentation

前視圖控制器的視圖即將 被添加到視圖層次和任何動畫用於顯示視圖配置 之前,此方法被調用。您可以覆蓋此方法以執行與顯示視圖相關的自定義 任務。例如,您可以使用此方法將狀態欄的方向或樣式更改爲 與所呈現視圖的方向或樣式相協調。 如果您重寫此方法,則必須在您的 實施中的某個時刻調用super。

因此,即使視圖層次沒有完全設置,也不能添加動畫。

0
Write your code in viewDidAppear method.As your table view is loaded 
then after you should call the method scrollToRowAtIndexPath . Then 
your animation will be performed.And if you want to use in 
viewWillAppear , then You can try to reload your tableView and then 
write code for scrollToRowAtIndexPath 
+0

嗨,感謝您的回覆,但是這並不能清除錯誤。無論使用ViewWillAppear還是ViewDidAppear,我都會得到相同的錯誤。 – Kitcc

+0

嗨,你有沒有嘗試過你的代碼後重新加載tableview。 ? –

+0

是的,我在代碼導致錯誤之前,重新加載到ViewDidAppear,但仍然得到錯誤。或者你打算把它放在其他地方? – Kitcc

0

你或許應該使用viewDidLoad方法用於滾動,如果你的數組數爲0(空數組),它會拋出一個錯誤。無法滾動到索引-1處的單元格。