如何将字符串从根视图控制器传递到另一个视图?

时间:2011-09-02 22:18:38

标签: iphone ios ios4 uitableview uiviewcontroller

我正在编写一个从第一个视图(RootViewController)获取用户输入的iphone应用程序,然后需要将输入传递给“结果”View Controller,这是另一个使用输入查询的视图服务器,解析JSON字符串并在UITableView中显示结果。我坚持如何“发送”这些字符串(从RootViewController上的用户输入)到第二个ViewController ...任何想法?

提前谢谢

的Stephane

3 个答案:

答案 0 :(得分:4)

有三种方法可以执行此操作,具体取决于视图的设置方式。

首先,您可以使用NSNotificationCenter发布字符串通知。另一个视图将注册为通知的观察者,并可在发布时收集信息。

其次,如果第一个视图控制器由第一个显示,即您分配/初始化VC并使用导航控制器显示它,则可以在第二个VC中创建属性并从根目录设置它。在第二个VC的标题中,您将创建以下内容:

NSString *someString;

@property (nonatomic, retain) NSString *someString;

然后在实现文件中@synthesize someString;。这样做可以让您在显示视图之前设置值。

最后,如果视图不相关,就像在根中没有呈现第二个VC那样,您将创建从根到第二个VC的IBOutlet。假设您在上一个解决方案中设置了属性,那么您可以调用self.secondVC.someString = myStringToPass;

行的内容

希望其中一个帮助

编辑:已实现我已注释掉指向NSNotificationCenter的链接.... oops

答案 1 :(得分:2)

在第二个视图控制器中,创建一个NSString实例以接收值并在您要显示此控制器时设置它,例如在tableView:didSelectRowAtIndexPath:方法中。 RootViewController.h

@interface RootViewController : UITableViewController
{
    NSString *stringToPass;
}

@property (nonatomic, retain) NSString *stringToPass;

@end

RootViewController.m

#import "SecondViewController.h"

@implementation RootViewController

@synthesize stringToPass;

// Other code goes here...

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // for example first cell of first section
    if (indexPath.section == 0 && indexPath.row == 0)
    {
        SecondViewController *second = [[SecondViewController alloc] initWithStyle:UITableViewStyleGrouped];
        // here you pass the string
        second.receivedString = self.stringToPass;
        [self presentModalViewController:second animated:YES];
        [second release];
    }
}
@end

SecondViewController.h

@interface SecondViewController : UITableViewController
{
    NSString *receivedString;
}

@property (nonatomic, retain) NSString *receivedString;

@end

SecondViewController.m

@implementation SecondViewController

@synthesize receivedString;

// methods to use the string goes here

@end

我还没有测试过这段代码......我已经记得它了:)

答案 2 :(得分:1)

对第二个视图控件进行子类化并编写自定义init方法。

-(id)initWithMyCustomValueString:(NSString*)string;

并将数据传递给它。


确保在secondViewController上创建iVar或属性以从中读取数据。

相关问题