2011-08-27 61 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。相反,您应该使用一个独特的对象应用程序范围来访问该值。

相关问题