Iphone 如何将NSSString从RootViewController传递到另一个视图?
我正在编写一个iphone应用程序,它从第一个视图RootViewController获取用户输入,然后将输入传递到结果视图控制器,结果视图控制器是另一个视图,它使用输入查询服务器、解析JSON字符串并在UITableView中显示结果。我被困在如何将这些字符串从RootViewController上的用户输入发送到第二个ViewController上…有什么想法吗 提前ThxIphone 如何将NSSString从RootViewController传递到另一个视图?,iphone,ios,ios4,uitableview,uiviewcontroller,Iphone,Ios,Ios4,Uitableview,Uiviewcontroller,我正在编写一个iphone应用程序,它从第一个视图RootViewController获取用户输入,然后将输入传递到结果视图控制器,结果视图控制器是另一个视图,它使用输入查询服务器、解析JSON字符串并在UITableView中显示结果。我被困在如何将这些字符串从RootViewController上的用户输入发送到第二个ViewController上…有什么想法吗 提前Thx Stephane为第二个视图控件创建子类,并编写一个自定义init方法 -(id)initWithMyCustomVa
Stephane为第二个视图控件创建子类,并编写一个自定义init方法
-(id)initWithMyCustomValueString:(NSString*)string;
并将您的数据传递给它
请确保在secondViewController上创建iVar或属性以从中读取数据。根据视图的设置方式,有三种方法可以执行此操作 首先,可以使用发布字符串通知。另一个视图将注册为通知的观察者,并可以在发布通知时收集信息 其次,如果第二个视图控制器由第一个视图控制器显示,即,您alloc/init VC并使用导航控制器显示它,那么您可以在第二个VC中创建一个属性,并从根目录进行设置。在第二个VC的标题中,您将创建以下内容:
NSString *someString;
及
然后@合成一些字符串;在实现文件中。这样做可以在显示视图之前设置值
最后,如果视图不相关,如第二个VC中的视图不是由根显示的,那么您将创建一个从根到第二个VC的IBOutlet。假设您像上一个解决方案中那样设置了属性,那么您可以调用self.secondVC.someString=myStringToPass
希望其中一个能帮上忙
编辑:意识到我已经注释掉了指向NSNotificationCenter的链接…oops在第二个视图控制器中,创建一个NSString实例以接收值,并在要显示此控制器时进行设置,例如在tableView:didSelectRowAtIndexPath:方法中。 RootViewController.h
@interface RootViewController : UITableViewController
{
NSString *stringToPass;
}
@property (nonatomic, retain) NSString *stringToPass;
@end
@interface SecondViewController : UITableViewController
{
NSString *receivedString;
}
@property (nonatomic, retain) NSString *receivedString;
@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 RootViewController : UITableViewController
{
NSString *stringToPass;
}
@property (nonatomic, retain) NSString *stringToPass;
@end
@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
我还没有测试过这个代码。。。我记得写过:有效,但丑陋。我同意为字符串设置一个属性,但是如果一个对象正在创建另一个对象,也可以调用一个普通的初始化器,然后设置该对象的属性。我很乐意。总是很乐意帮忙