2010-08-10 43 views
1

我想從父視圖中加載數據(字符串數組)到一個呈現模態視圖的子視圖中的一組UITextFields。如何將數據從父視圖傳遞給兒童時打開?

我知道如何從孩子傳遞給父母,我相信以其他方式更容易,但我不知道如何。

更新:更新移除,因爲我發現這個問題(模態的視圖的雙釋放)

回答

2

改寫爲子視圖控制器init方法。

- (id) initWithStrings:(NSArray *)string { 
    if (self = [super init]) { 
     // Do stuff.... 
    } 
    return self; 
} 

然後在父:

MyChildViewController *vc = [[[MyChildViewController alloc] initWithStrings: strings] autorelease]; 
+0

謝謝!工作很好,但出現了兩個問題。 1.父母.m文件給我一個警告:找不到'-initWithStrings:'方法。我需要在哪裏定義它? 2.一旦子視圖已經加載,並且我已經使用viewDidLoad來填充我的UITextFields,當我點擊任何其他UI元素(按鈕,文本字段)時,應用程序凍結,我得到「sharedlibrary apply-load-rules all (gdb)「在我的控制檯和我的線程1有很多引用」prepareForMethodLookup「 想法? – 2010-08-10 16:37:36

+0

把它放在.h文件中也是如此: - (id)initWithStrings:(NSArray *)string; – 2010-08-10 17:04:04

+0

不確定關於#2,您是否獲得了EXC_BAD_ACCESS? – 2010-08-10 18:22:57

0

兩種方法,你可以做到這一點:

1.Override init方法馬特暗示你的孩子

2.創建領域並將這些值傳遞給您的文本字段。

@interface ChildViewController : UIViewController{ 
    NSArray *strings; 
    UITextfield *textField1; 
    UITextfield *textField2; 
} 
... 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    textField1.text = [strings objectAtIndex:0]; 
    textField2.text = [strings objectAtIndex:1]; 
} 

然後在父類:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    ChildViewController *childController = [[ChildViewController alloc] init]; 
    childController.strings = your_array_of_strings; 
    [self.navigationController pushViewController:childController animated:YES]; 
    [childController release]; 

} 
0
- (id)initWithDataObject:(YourDataObjectClass *)dataObject { 
    if (self = [super init]) { 
     self.dataObject = dataObject; 
     // now you can do stuff like: self.myString = self.dataObject.someString; 
     // you could do stuff like that here or if it is related to view-stuff in viewDidLoad 
    } 
    return self; 
} 
0

如果你想獲得真正看中的,你可以讓你的孩子視圖的委託。

@protocol MyChildViewDelegate 
- (NSArray*)getStringsForMyChildView:(MyChildView*)childView; 
@end 

@interface MyChildView : UIView 
{ 
    id <MyChildViewDelegate> delegate; 
    ... 
} 

@property (nonatomic, assign) id <MyChildViewDelegate> delegate; 
... 
@end 

您認爲這些地方,你會索要字符串:

- (void)viewDidLoad 
{ 
    ... 
    NSArray* strings = [delegate getStringsForMyChildView:self]; 
    ... 
} 

然後在你的控制器(或者其它任何),你可以這樣做:

myChildView = [[MyChildView alloc] initWith....]; 
myChildView.delegate = self; 

... 

- (NSArray*)getStringsForMyChildView:(MyChildView*)childView 
{ 
    return [NSArray arrayWithObjects:@"one", @"two", @"three", nil]; 
} 

這可能是一個小在這種情況下矯枉過正,但這也是UITableViews的做法:他們有一個數據源委託來提供它們的內容。

相關問題