[英]Passing array to another view
我是xcode的新手。 我試圖將數組從一個視圖傳遞到另一個。 我想將ProfileViewController中的整數profileid
傳遞給FavouritesViewController中的數組。 加載FavouritesViewController后,日志將顯示該數組。
這是我的代碼:
ProfileViewController.h
- (IBAction)AddFavouritesClicked:(id)sender;
ProfileViewController.m
@synthesize profileid;
int profileid = 0;
- (IBAction)AddFavouritesClicked:(id)sender {
FavouritesViewController *favController = [[FavouritesViewController alloc]init];
[favController.favouritesArray initWithObjects:[NSNumber numberWithInt:profileid], nil];
NSLog(@"%@", favController.favouritesArray);
}
FavouritesViewController.h
@interface FavouritesViewController : UITableViewController
{
NSMutableArray *favouritesArray;
}
@property(nonatomic, retain)NSArray *favouritesArray;
@end
FavouritesViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"%@", favouritesArray);
}
到目前為止, favouritesArray
值始終為null
任何幫助將不勝感激。 提前致謝!
這是我每次單擊Addtofavoutites
按鈕時的日志
2013-01-27 22:54:52.865 Ad&Promo[8058:c07] (
2
)
2013-01-27 22:56:10.958 Ad&Promo[8058:c07] (
2
)
2013-01-27 22:56:11.705 Ad&Promo[8058:c07] (
2
)
2013-01-27 22:56:12.191 Ad&Promo[8058:c07] (
2
)
但是我希望它看起來像這樣。
2013-01-27 22:54:52.865 Ad&Promo[8058:c07] (
2,2,2,2
)
您沒有分配指針,並且缺少了alloc方法,請按照以下方式進行操作:
favController.favouritesArray=[[NSArray alloc]initWithObjects:[NSNumber numberWithInt:profileid], nil];
首先,您應該檢查數組創建的語法。 它應該是:
favController.favouritesArray = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:profileid], nil];
我猜,僅此一項並不能解決您的問題
這是一個非常典型的錯誤,在以下2條語句中顯示在SO上:
FavouritesViewController *favController = [[FavouritesViewController alloc]init];
favController.favouritesArray = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:profileid], nil];
您正在分配一個新的FavouritesViewController
。 這與您已經在應用程序中初始化的任何其他FavouritesViewController
無關。 這就解釋了為什么其內部數組為空。
您需要做的是讓ProfileViewController
實例知道您的FavouritesViewController實例(而不是在前者實例化后者的私有實例)。
因此,只需在ProfileViewController
內定義FavouritesViewController
屬性,然后對其進行正確初始化。 然后,您將可以執行以下操作:
- (IBAction)AddFavouritesClicked:(id)sender {
self.favController.favouritesArray = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:profileid], nil];
}
這將設置您需要設置到另一個視圖控制器中的值。
編輯:
針對這種需求的更好設計是使用模型 (例如在模型視圖控制器中)。
無需讓兩個控制器中的一個知道另一個,您可以創建一個新類(模型)來負責將所有共享數據保存在應用程序中。
您可以從應用程序中的任何其他類訪問該類,以便他們可以設置和獲取其存儲的數據。
此類可能是單身人士:
[MyModel sharedModel].favArray = ...
也可以是只公開類方法的類,例如:
[MyModel setFavArray:...];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.