2010-07-13 128 views
0

我有我的TableController的問題。TableViewController - 從數據庫檢索數據

當我打電話的cellForRowAtIndexPath()我能夠從數據庫類檢索信息:

myGroupsAppDelegate *appDelegate = (myGroupsAppDelegate *)[[UIApplication sharedApplication] delegate]; 
myGroupsDB *mgdb = [ appDelegate.groups_db objectAtIndex:indexPath.row ]; 
cell.textLabel.text = mgdb.group_name; 
[mgdb release]; 

但如果我嘗試調用從didSelectRowAtIndexPath方法相同()我得到一個錯誤。我需要兩個值傳遞給視圖,我用這個代碼:

SingleGroupView *sgv = [[SingleGroupView alloc] initWithNibName:@"SingleGroupView" bundle:[NSBundle mainBundle]]; 

myGroupsAppDelegate *appDelegate = (myGroupsAppDelegate *)[[UIApplication sharedApplication] delegate]; 
myGroupsDB *mgdb = [ appDelegate.groups_db objectAtIndex:indexPath.row ]; 

sgv.groupID = mgdb.id_group; 
sgv.groupName = mgdb.group_name; 

[mgdb release]; 

當我嘗試分配mgdb.id_group到sgv.groupID我得到一個EXC_BAD_ACCESS。看起來mgdb是空的。

-------------- CHANGE ------------------

一個Build後和分析,示出編譯器「對此時沒有所有者的對象的引用計數進行減法「。但是,我在這裏創建,不是本地嗎?所以我加了保留:

myGroupsDB *mgdb = [[ appDelegate.groups_db objectAtIndex:indexPath.row ] retain]; 

,現在它的工作原理,但是,如果我嘗試調用相同的代碼(只是按下行,更改視圖,再回來,然後按行)沒有日誌應用chrash和用相同的信息。

有什麼建議嗎?

感謝, 安德烈

回答

0

我找到了(我?你)的解決方案。

的cellForRowAtIndexPath()是:

myGroupsAppDelegate *appDelegate = (myGroupsAppDelegate *)[[UIApplication sharedApplication] delegate]; 
myGroupsDB *mgdb = (myGroupsDB*)[ appDelegate.groups_db objectAtIndex:indexPath.row ]; 

cell.textLabel.text = mgdb.group_name; 

和didSelectRowAtIndexPath方法()是:

myGroupsAppDelegate *appDelegate = (myGroupsAppDelegate *)[[UIApplication sharedApplication] delegate]; 
myGroupsDB *mgdb = (myGroupsDB *)[appDelegate.groups_db objectAtIndex:indexPath.row]; 

我除去二者[釋放],因爲,如在內存管理編程指南所描述的,我不擁有mgdb實例,所以我不負責重新定義所有權。所以,我不知道爲什麼使用alloc或newObject在內存中創建新實例並不是強制的,但是如果我不是所有者,我不會釋放對象。我還添加了mgdb的投射,不是必要的,而是良好的做法。

bye, Andrea

1

看來你是過度釋放mgdb對象。

如果你沒有得到從方法的名字與allocnew開始和對象,如果你不發送retain消息給它,那麼就意味着你沒有「自己」的對象和你應該不是release吧。

你可以在Memory Management Programming Guide瞭解更多。

注意:當你得到EXC_BAD_ACCESS這意味着你正在訪問一個你不允許訪問的內存區域(在這種情況下,你不允許訪問它,因爲它可能已被解除分配)。