爲了解決這些誰說「這是一個壞主意」,在我的情況,我需要這是我對我的UITableViewCell
一個按鈕,按下時,是SEGUE另一種觀點。由於這不是電池本身的選擇,所以[self.tableView indexPathForSelectedRow]
不起作用。
這讓我兩個選擇:
- 商店,我需要傳遞到表格單元本身的視圖對象。雖然這會起作用,但它會擊敗我擁有
NSFetchedResultsController
的點,因爲我不需要想要將所有對象存儲在內存中,尤其是在表很長的情況下。
- 使用索引路徑從提取控制器中檢索項目。是的,我不得不通過黑客來找出
NSIndexPath
,但它比存儲內存中的對象更便宜。
indexPathForCell:
是用正確的方法,但這裏是我會怎麼做(假設這段代碼在UITableViewCell
子類來實現:
// uses the indexPathForCell to return the indexPath for itself
- (NSIndexPath *)getIndexPath {
return [[self getTableView] indexPathForCell:self];
}
// retrieve the table view from self
- (UITableView *)getTableView {
// get the superview of this class, note the camel-case V to differentiate
// from the class' superview property.
UIView *superView = self.superview;
/*
check to see that *superView != nil* (if it is then we've walked up the
entire chain of views without finding a UITableView object) and whether
the superView is a UITableView.
*/
while (superView && ![superView isKindOfClass:[UITableView class]]) {
superView = superView.superview;
}
// if superView != nil, then it means we found the UITableView that contains
// the cell.
if (superView) {
// cast the object and return
return (UITableView *)superView;
}
// we did not find any UITableView
return nil;
}
PS我真正的代碼做這個訪問的所有從表中的觀點,但我給的,爲什麼有人會想直接做這樣的事情在表格單元格爲例
就像從你的其他[問題](http://stackoverflow.com/questions/15711645/how-to-get-uitableview-from-uitableviewcell)獲取單元格中的「UITableView」 - 爲什麼?這看起來像是一個糟糕的設計決定的代碼味道 - 對於一個單元來說,它沒有太多合法的用例來知道它是否是indexPath,或者它是否在屏幕上。 –
我同意Paul.s的評論。你應該說明你爲什麼要這樣做,因爲你想要做的事可能是一個壞主意。 – rdelmar
@ Paul.s我在問題中發佈了我的程序設計。這可能是不好的編程實踐,在這種情況下,如果你可以提出一個替代方案,那將是非常有用的。一般來說,我對可可非常陌生,對編程也比較陌生。 –