這是一個簡單的問題:如何在兩個不同的視圖控制器之間傳遞信息?
我有2個不同的視圖控制器,每個都有自己的數據存儲在其.m文件。 我想獲取一個值,例如,在ViewController1中聲明的整數值(int i=3;
)並將其傳遞給ViewController2,以便我可以在第二個視圖控制器中使用該值。
任何人都可以請告訴我該怎麼做嗎?
這是一個簡單的問題:如何在兩個不同的視圖控制器之間傳遞信息?
我有2個不同的視圖控制器,每個都有自己的數據存儲在其.m文件。 我想獲取一個值,例如,在ViewController1中聲明的整數值(int i=3;
)並將其傳遞給ViewController2,以便我可以在第二個視圖控制器中使用該值。
任何人都可以請告訴我該怎麼做嗎?
2014編輯 - 萬一有人發生在此,不聽我的。 「更好的方式」確實是最好的方法。
好路子 - 在ViewController2
創建自己的initWithI方法更好的方式 - 創建ViewController2像往常一樣,然後設置值的屬性。
最佳方式 - 這是一種代碼異味,您將數據與ViewController緊密耦合。改用CoreData或NSUserDefaults。
如果您將ViewController1嵌入到UINavigationController中,這是一個非常常見的用例。裏面ViewController1,添加以下代碼要顯示ViewController2(例如在發生作用):
ViewController2 *controller = [[ViewController2 alloc] initWithNibName:<nibName> bundle:nil];
[controller setData:<your shared data>];
[self.navigationController pushViewController:controller animated:YES];
[controller release];
導航控制器將完成剩餘的工作。
用該值初始化新的視圖控制器。
- (id)initWithValue:(int)someValue {
if (self = [super initWithNibName:@"MyViewController" bundle:nil]) {
myValue = someValue;
}
return self;
}
從其他視圖控制器
然後(假設這個其他視圖控制器由UINavigationController
擁有)
- (void)showNextViewControler {
MyViewController *vc = [[[MyViewController alloc] initWithValue:someValue] autorelease]
[self.navigationController pushViewController:vc animated:YES];
}
和/或初始化後做了,創建一個方法或屬性,讓您設置它。
- (void)setSomeValue:(int)newValue {
myValue = newValue;
}
然後
- (void)showNextViewControler {
MyViewController *vc = [[[MyViewController alloc] initWithNibName:@"Foo" bundle:nil] autorelease]
[vc setValue:someValue]
[self.navigationController pushViewController:vc animated:YES];
}
NSUserDefaults聽起來是最簡單的解決方案。 – Sagiftw 2010-04-15 16:32:29