2011-08-27 59 views
0

我在我的firstViewController定義爲UITextField如下傳的UITextField文本從一個視圖到另一個

// firstViewController.h 
IBOutlet UITextField *PickUpAddress 
@property (nonatomic, retain) UITextField *PickUpAddress; 

//firstViewController.m 
@synthesize PickUpAddress; 

// Push secondView when the 'Done' keyboard button is pressed 
- (BOOL)textFieldShouldReturn:(UITextField *)textField { 
    [textField resignFirstResponder]; 
    if (textField == PickUpAddress) { 
     SecondViewController *secondViewController= [[SecondViewController alloc] 
                 initWithNibName:@"SecondViewController" 
                 bundle:nil]; 
     secondViewController.hidesBottomBarWhenPushed = YES; 
     [self.navigationController pushViewController:secondViewController animated:YES]; 
     [secondViewController release]; 
    } 

    return NO; 
} 

然後我試圖viewWillAppear中

期間以檢索它在我secondViewController
- (void)viewWillAppear:(BOOL)animated { 
    BookingViewController *bookingViewController = [[BookingViewController alloc] init]; 
    NSString *addressString = [[NSString alloc] init]; 
    addressString = bookingViewController.PickUpAddress.text; 
    NSLog(@"addressString is %@", bookingViewController.PickUpAddress.text); 
} 

但它返回在我的控制檯上爲NULL。爲什麼? 在此先感謝:)

回答

2

在secondViewController.h添加

NSString *text; 

@property (nonatomic, retain) NSString *text; 

-(void)setTextFromText:(NSString *)fromText; 
在secondViewController.m

[self.navigationController pushViewController:secondViewController animated:YES]; 

添加以下

- (void)setTextFromText:(NSString *)fromText 
{ 
    [text release]; 
    [fromText retain]; 
    text = fromText; 
} 
在firstViewController.m

添加

[secondViewContoller setTextFromText:PickUpAddress.text]; 

現在讓我來解釋一下代碼。

您正在將NSString添加到第二個視圖,我們將在其中存儲來自UITextField的文本。然後,我們寫了一個方法,它將從其他一些NSString中設置NSString。 將secondViewController推送到navigationController之前,您只需調用該方法即可從PickUpAddress.text設置我們的文本。 希望有所幫助。

+0

您的解決方案確實有效,但爲什麼我們需要使用方法來設置字符串?我們可以只用'@synthesize myString'並設置屬性,'secondViewController.myString = @「stringToSet」;'我可以知道這種方法與你的區別嗎?我看到'釋放'&'保留'被使用,並使我困惑。 –

+0

我認爲我的方法與你的方法 – davartan

+0

@MaTaKazer沒有什麼區別,如果Davartan給你解決方案,請投票。 – azizbekian

0

問題出現在您的代碼中。您正在創建新對象bookingViewController,以檢索textField值。所以它顯然會提供NULL。相反,您應該使用一個獨特的對象應用程序範圍來訪問該值。

相關問題