我在mainViewController.m中公开声明了NSString,NSString *characterString
,在我执行[self performSegueWithIdentifier:@"segueToFinal" sender:self];
之前,我用最新数据更新了这个characterString
。像这样:
characterString=[NSString stringWithFormat:@"final string %@",truncatedString];
[self performSegueWithIdentifier:@"segueToBlueprints" sender:self];
当新视图控制器完成显示时,用户将按下一个按钮,该按钮将调用一个方法,该方法将需要characterString
以及可能来自该先前视图控制器的其他公开声明的实例变量。我正在尝试[[mainViewController alloc]getCharacterString]
(getCharacterString
是一个在mainViewController中实现的方法)但当然创建了一个新的mainViewController实例并没有解决问题。
如何访问当前位于' characterString'的数据?和旧视图控制器中的其他变量?
答案 0 :(得分:3)
将所有全局变量保存在AppDelegate中:
YourAppDelegate.h
@interface BTAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) NSString * characterString;
@end
YourViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
YourAppDelegate* app = (YourAppDelegate*)[UIApplication sharedApplication].delegate;
app.characterString = @"Hello";
}
YourSecondViewController.m
- (IBAction)pressButton:(id)sender{
YourAppDelegate* app = (YourAppDelegate*)[UIApplication sharedApplication].delegate;
app.characterString = @"Hello2";
}
等
答案 1 :(得分:2)
试试这个:
@interface NewVC :UIViewController
@property (nonatomic) NSString *newCharacterString;
@end
现在在mainViewController中导入NewViewController类:
#import "NewViewController.h"
.......
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
NewViewController *destinationViewController = [segue destinationViewController];
destinationViewController.newCharacterString = self.characterString;
}
您可以通过 newCharacterString 属性访问 NewViewController 中的字符串值。 HTH:)
答案 2 :(得分:0)
我唯一能想到的是将视图控制器中的旧数据与segue一起传递。或者,如果您想要保留多个属性,甚至可以传递整个旧视图控制器。
在新的VC(被攻击者)中,添加一个你要保留的属性(旧的VC(被引用的),例如NSString *
。
@interface NewVC :UIViewController
@property (nonatomic) NSString *newCharacterString;
@end
然后,当你正在进行思考时,只需将值传递给新的VC。
characterString=[NSString stringWithFormat:@"final string %@",truncatedString];
newViewControllerIWantToPassAValueTo.newCharacterString = characterString;
// passes new string forward to View Controller
[self performSegueWithIdentifier:@"segueToBlueprints" sender:self];
答案 3 :(得分:0)
为什么你不将这个characterString传递给secondViewController
在SecondViewController中:
@interface SecondViewController:UIViewController
@property (strong, nonatomic) NSString *newCharacterString;
@end
在MainViewController中:
[self performSegueWithIdentifier:@"segueToBlueprints" sender:self];
您必须将preparePerform Segue添加到MainViewController
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Make sure your segue name in storyboard is the same as this line
if ([[segue identifier] isEqualToString:@"YOUR_SEGUE_NAME_HERE"])
{
SecondViewController *vc = [segue destinationViewController];
// Pass any objects to the view controller here, like...
vc.newCharacterString = self.characterString;
}
}
你可以在SecondViewController中使用newCharacterString而无需回调到MainViewController