我有一个包含三个页面的iPhone应用程序,每个页面都允许用户输入一些文本。在最后一页上,我想将所有三个字符串连接起来并打印出来。每个页面都有一个UIViewController
(名为PageXController
),我正在尝试将变量传递到最后一页。我目前尝试的方法不太有效。这是一个例子:
首先,我将一个字符串声明为实例变量 PageThreeController.h
@interface PageThreeController : UIViewController{
NSMutableString *string;
}
@property (nonatomic) NSMutableString *string;
接下来,我将以下内容添加到中PageOneController.h
,
#import "PageThreeController.h"
@interface PageOneController : UIViewController
@property (nonatomic) PageThreeController *pageThree;
在PageOneController
我然后尝试设置三个页面上的字符串实例变量;
- (IBAction)handleButton:(id)sender {
_pageThree = [[PageThreeController alloc] init];
_pageThree.from = [[NSMutableString alloc]init];
[_pageThree.from appendString:@"Hello World"];
NSLog(@"My string is %@ on page one.", _pageThree.from);
}
在NSLog
出我的字符串是打印'Hello World'
在一页上。但是当我PageThreeController.m
在连接前添加相同的NSLog时,'string'
是NULL
。
看来我正在制作的单独副本pageThreeViewController
。我该怎么做才能在第三页上更改字符串的实际值?我真的很新
在ViewControllers之间传递数据的最简单方法是使用AppDelegate,即使还有其他方法也是如此。
方法1-使用AppDelegate。在您的Appdelegate中添加以下行。
@property (strong,nonatomic) NSMutableString *str;
要从任何视图控制器访问变量,
MyAppdeleagte appDelegate=[[UIApplication sharedApplication]delegate];
NSMutableString *Stringdata=appDelegate.str;
方法2-指定对象。在此方法中,您可以像现在一样继续进行,只需要指定视图控制器实例即可。
让您可以从一个控制器导航到另一个控制器,例如从FirstController到Second。Firstcontroller.h
@interface FirstController : UIViewController{
NSMutableString *string;
}
@property (nonatomic) NSMutableString *string;
SecondController.h
@interface SecondController : UIViewController{
}
@property (strong,nonatomic) FirstController *firstScreen;
在FirstController的实现中,在导航到SecondController之前,必须在SecondController中指定实例。
在FirstController.m中
SecondController *nextScreen=[self.storyboard instantiateViewControllerWithIdentifier:@"SecondView"];
nextScreen.firstScreen=self;
然后在SecondController.m中,只需将String作为
_firstScreen.string;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句