2011-05-18 34 views
2

我有一個名爲PresidentsViewController的視圖控制器類,它在UITableView中設置數據。該數據的格式爲NSMutableArray,稱爲list。我有另一個課程,PresidentAddController,應該根據用戶輸入的有關總統的數據來處理將類型爲President的對象添加到此列表中。但是,我無法將對象添加到列表中。我已經確認用戶爲新總統輸入的數據正在被正確收集,因此它正在添加到導致問題的另一個類中的列表中。我認爲正確的代碼將一個對象添加到列表是:將對象添加到其他類的NSMutableArray中

[pvc.list addObject:newPresident]; 

不過,我不知道如何正確地創建參考/實例/? (這是pvc會是什麼)PresidentialViewController內的PresidentAddController,以便我可以正確地添加一個新的總統到列表中。我沒有爲此使用Interface Builder,因爲它只是一個UITableView。

在這種情況下,如何將總統添加到列表中?

編輯:這裏是如何的數組初始化:

@property (nonatomic, retain) NSMutableArray *list; 

這裏是PresidentAddController是如何被設置在PresidentsViewController:

PresidentAddController *childController = [[PresidentAddController alloc] initWithStyle:UITableViewStyleGrouped]; 
childController.title = @"Add President"; 
[self.navigationController pushViewController:childController animated:YES]; 
[childController release]; 
+0

你可以發佈你的代碼初始化你的可變數組並設置其屬性? – Krishnan 2011-05-18 04:37:58

+0

我剛剛編輯了包含該問題的問題。 – epaps 2011-05-18 04:59:51

回答

1

指針添加到PresidentAddController這樣:

// in @interface 
PresidentsViewController *listController; 

@property (nonatomic, assign) PresidentsViewController *listController; 

// in @implementation 
@synthesize listController; 

然後,當你實例化你PresidentAddController,設置指針:

PresidentAddController *childController = 
    [[PresidentAddController alloc] 
    initWithStyle:UITableViewStyleGrouped]; 
childController.title = @"Add President"; 
childController.listController = self; 
[self.navigationController pushViewController:childController animated:YES]; 
[childController release]; 

,那麼你可以在PresidentAddController[listController.list addObject:newPresident];

編輯:childController.listController = self電話[childController setListController:self],進而讀取您實現@synthesize d方法,並設置指針*listController指向當前類(如果你在PresidentsViewController類編寫代碼,然後self是怎麼回事成爲PresidentsViewController的當前實例)。

我之所以使用assign是因爲如果您要使用retain,那麼當您將listController設置爲self時,它實際上會保留對該對象的擁有引用。如果您嘗試釋放PresidentsViewController,這可能會導致各種問題,因爲如果您擁有PresidentAddController中的擁有引用,那麼它將不會釋放,直到該引用也被釋放。使用assign可確保如果您在PresidentAddController消失之前釋放了PresidentsViewController,它將被正確釋放。當然,也許你想保持在這種情況下,在這種情況下使用retain這裏也沒有問題。

+0

感謝您的迴應 - 請參閱編輯PresidentAddController的初始化過程。是的,你的第一個問題。 – epaps 2011-05-18 04:57:18

+0

在澄清之後更新了答案:) – darvids0n 2011-05-18 05:05:38

+0

This Works!你介意準確地解釋一下'childController.listController = self;'的作用嗎?這似乎是我需要的代碼行。另外,對於@property聲明,是否有必要將它設置爲「assign」,因爲您將設置爲「self」? – epaps 2011-05-18 05:09:28

0

我的懷疑是你有一個屬性定義爲@property (nonatomic,copy) NSMutableArray *list;你是否正在嘗試將對象添加到數組中?如果是這樣,可能是因爲複製修飾符正在返回數組的不可變副本。嘗試創建一個方法,將該對象,並將其添加到列表中,而不使用self.list ...只是[list addObject],如果這有效,那麼這是你的問題。

+0

不,我沒有得到一個例外。我相信這是首先訪問PresidentsViewController類的問題,但我不確定。設置引用/實例的正確方法是什麼,而不必再次分配/ init PresidentsViewController,因爲這不起作用? – epaps 2011-05-18 04:54:20

相關問題