有谁能告诉我为什么我无法在 View Controller 之间传递数据?
非常感谢任何帮助!
我从 NSMutableArray 获取对象,然后访问 placeId 属性。然后我希望将其传递给下一个 View Controller (BIDCCreateViewController),但我做不到。 Null 总是从下一个 View Controller 记录下来。
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
BIDDCCreateViewController *biddccCreateViewController = [[BIDDCCreateViewController alloc]init];
BIDBusinessModel *tempObjStore = [self.linkedBusinessParseModelArray objectAtIndex:indexPath.row];
biddccCreateViewController.placeId = tempObjStore.placeId;
NSLog(@"tempObjStore in didselectrow: %@", tempObjStore.placeId);
}
#import <UIKit/UIKit.h>
@interface BIDDCCreateViewController : UIViewController
@property (strong, nonatomic) NSString *placeId;
@end
#import "BIDDCCreateViewController.h"
@implementation BIDDCCreateViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSLog(@"SUCCESSFULLY PASSED PLACE ID: %@", self.placeId);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
我的输出来自日志如下:
2013-09-24 14:01:49.208 CouponLocation[827:a0b] tempObjStore in didselectrow: 1f068b8d2b6a13daf9be5eddee5cb32585b76377
2013-09-24 14:01:49.209 CouponLocation[827:a0b] SUCCESSFULLY PASSED PLACE ID: (null)
没有传递任何东西。当我在 BIDCCCreateViewConroller 中设置字符串并记录它时,它工作正常。如您所见,我试图从中传递的 viewcontroller 中的字符串很好。这在“didselectrow 中的 tempOjcStore”日志中进行了演示。所以那里有一个字符串,但它没有被传递,并且另一个 viewcontroller 中的字符串似乎没有任何问题,因为我能够从内部更改它并记录。
不知何故,它没有被传输。
有什么建议吗?
最佳答案
您在错误的对象上设置了值:biddccCreateViewController
是您方法的本地值,它不是稍后显示的 Controller ,当 segue 被触发时(或通过它的任何方法)你打开实际的 View Controller )。
不要将代码放在 didSelectRowAtIndexPath
中,而是将代码放在 prepareForSegue
中。您可以从那里访问目标 View Controller ,如下所示:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if([segue.identifier isEqualToString:@"openDetails"]){
UITableViewCell *cell = (UITableViewCell *) sender;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
BIDDCCreateViewController *biddccCreateViewController = (BIDDCCreateViewController*)segue.destinationViewController;
BIDBusinessModel *tempObjStore = [self.linkedBusinessParseModelArray objectAtIndex:indexPath.row];
biddccCreateViewController.placeId = tempObjStore.placeId;
}
}
最后,显示 placeId
值的正确位置是 viewWillAppear
,而不是 viewDidLoad
,因为 View 加载发生在您可以之前在 Controller 上设置 placeId
。
关于ios - 无法在 View Controller 之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18982609/