如何将字符串值传递给以前的viewController

时间:2013-08-13 13:04:19

标签: iphone ios

我在secondViewController中有UITextField,在同一视图中有一个按钮。

我希望将UITextField文本作为firstViewController的字符串。

这是我的代码。

SecondViewController.m

-(void)backToFirstView
{

NSString *str=disTxtFld.text;
FirstView *firstView=[[FirstView alloc]init];
firstView.discountStr=str;
[self.navigationController popViewControllerAnimated:YES];

}

FirstViewController.h

@property (nonatomic,strong) NSString   *disStr;

FirstViewController.m

@synthesize disStr;

 -(void)viewWillAppear:(BOOL)animated
 {
 NSLog(@"discount:%@",disStr);
 }

当我试图在第一个视图中打印该字符串时..显示空值..

任何建议......

4 个答案:

答案 0 :(得分:3)

最简单的方法是使用委托。请看这里: http://krodev.wordpress.com/2012/10/08/objective-c-delegates/ 它是如何定义和实现委托的一步一步指导。

代表们习惯于做你正在寻找的事情。

答案 1 :(得分:0)

最佳方法:在故事板中使用展开segue返回上一个VC并传递数据。有关此内容的更多信息,请观看2012年Storyboards WWDC会话。

其他方式:使用委托模式。在SecondViewController类中创建一个名为SecondViewControllerDelegate的协议。给它类似“secondViewControllerDidFinish:”和“secondViewControllerDidCancel:”的方法。让FirstViewController符合该协议并为这些方法提供实现。在这些实现中,请确保已解除呈现的SecondViewController。在SecondViewController中,创建一个id为。

的委托属性

当FirstViewController呈现SecondViewController时,让它自己设置为SecondViewController的委托。当SecondViewController完成需要完成的任何工作时,让他们调用委托方法并传入相关数据。

答案 2 :(得分:0)

在1st-viewController中创建一个函数

-(void)setStringFromSecondView:(NSStirng *)_value{
my_String=[NSString stringwithFormate:@"%@",_value];
}

并将其添加到头文件

-(void)setStringFromSecondView:(NSStirng *)_value;

现在在secondViewController中添加一个委托变量

{
id delegateOfPrevious;
}

-(void)setDelegate:(id)_delegate{
delegateOfPrevious=_delegate
}

现在,在第一个viewController中推送第二个视图控制器之前,你必须设置FirstView的委托这样

secondViewController *secondView=[[secondViewController alloc] init....];
secondView.setDelegate=self;

........... 现在每一件事都定了。你离成功只有一步之遥:

在弹出SecondViewController之前,您可以在第二个视图控制器中调用此函数,它将在第一个视图控制器中设置该值。

[delegateOfPrevious setStringFromSecondView:textView.txt];

不要忘记在SecondViewController中包含firstViewController.h。 我前一天为自己的项目做了这件事,而且工作正常。

答案 3 :(得分:-2)

一种最好的方法是在app delegate.h中将你的nsstring声明为全局,然后合成它 在第二个视图控制器中填充数据,然后尝试在第一个视图控制器中访问此nsstring。