如何将NSString值从SecondViewController传递给FirstViewController?

时间:2013-10-18 04:59:19

标签: ios objective-c

我创建了一个基于Tab的应用程序,其中FirstViewController具有Display UILabel属性,而且,我有SecondViewController选项卡(All in Sotoryboard),它保存数据以显示在FirstViewController上,但我似乎无法实现这一点没有得到错误。我尝试使用代理但最终崩溃了我的应用程序。

这是我在我的应用上遇到的第一个问题。任何人都可以解释这个问题吗?

SecondViewController中的任何示例将NSString值从View本身传递给FirstViewController?

示例:

NSString *valueString; // This String holds a value to display onto the First View Controller when i tap a save Button on the same Second View controller.

在第一个视图控制器中,我有一个名为:

的UILabel
  @property (strong, nonatomic) IBOutlet UILabel *displayValue;

连接到Storyboard中的UIlabel,但似乎无法使NSString * valueString将其数据显示在displayValue属性标签上。

这里的任何人都有最好的方法吗?如果需要,我会把代表放在哪里?

3 个答案:

答案 0 :(得分:0)

在第一个视图控制器.m文件中创建第二个视图控制器时:

secondViewController.delegage = self;

单击第二个视图控制器.m文件中的按钮时:

[delegate.displayValue setText:valueString];

在第二个视图控制器的.h中:

@property (strong, nonatomic) FirsViewController *delegate;

答案 1 :(得分:0)

实现目标有两种方法。 1.为共享数据创建单例类(在您的情况下,您希望从一个ViewController传递到另一个ViewController的字符串)。

2.Declare appDelegate class中的共享数据。(你应该使用第二个mathod,因为你只想共享字符串。)

在appDelegate.h中声明你的字符串

@property(retain,nonatomic) NSString *YourString;

现在在你的第二个viewController中分配你想要的值。

AppDelegate *appdelegate = [[UIApplication sharedApplication] delegate];
appdelegate.YourString = @"Your VAlue";

现在从第一个ViewController访问相同的字符串。

 AppDelegate *appdelegate = [[UIApplication sharedApplication] delegate];



 self.yourLable.text = appdelegate.YourString;

我无法在这里附上源代码。您只需按照说明操作即可。

1.打开AppDElegate.h文件并粘贴以下代码。

@property(strong,nonatomic) NSString *SharedString;

2.现在打开SecondViewController.m并导入appDelegate.h

#import "AppDelegate.h"

3.在SeconViewController.m中使用您的值初始化sharedString

ViewDidLoad
{
 AppDelegate *appdelegate = [[UIApplication sharedApplication] delegate];
    appdelegate.SharedString=@"Any String";

}
  1. 打开FirstViewController.m并导入appDelegate.h

    #import“AppDelegate.h”

  2. 5.在FirstViewController.m中粘贴以下代码

    - (void)viewDidAppear:(BOOL)animated
    {
        AppDelegate *appdelegate = [[UIApplication sharedApplication] delegate];
        self.YouLable.text = appdelegate.SharedString;
        [super viewDidAppear:NO];
    
    }
    

答案 2 :(得分:-2)

尝试方式......

IN secondViewController

make the object of the FirstView

FirstView *fc=[[FirstView alloc]initWithNibName:@"FirstView" bundle: nil];
fc.displayValue.text= ValueString;