在 iOS 中的两个控制器之间传递变量

Pass variables between two controllers in iOS

我想从我的第一个控制器传递一些变量:

float user_distance;
UIImage *user;
float user_battery;
NSString *user_name;

到第二个控制器。 两者之间的联系是通过函数:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

以这种方式:

    UserViewController *secondViewController = [[UserViewController alloc] initWithNibName:@"UserViewController" bundle:nil];
[self.navigationController pushViewController:secondViewController animated:YES];

如何从这个函数中恢复值?

提前致谢!

在 .h 文件中将您需要的属性添加到第二个控制器..

//SecondController.h    
@interface SecondController : UIViewController
@property (nonatomic) float *property1;
@property (nonatomic, strong) UIImage *property2;
@property (nonatomic) float *property3;
@property (nonatomic, strong) NSString *property4;
@end

然后将第二个控制器的 .h 文件导入到第一个控制器的 .m 文件中。 并在推送第二个控制器之前设置属性。

//FirstController.m
#import "SecondController.h"
...
...
UserViewController *secondViewController = [[UserViewController alloc] initWithNibName:@"UserViewController" bundle:nil];

secondViewController.property1 = ;//your value here
secondViewController.property2 = ;//your value here
secondViewController.property3 = ;//your value here
secondViewController.property4 = ;//your value here

[self.navigationController pushViewController:secondViewController animated:YES];