gpt4 book ai didi

ios - 在 View Controller 之间传递数据

转载 作者:行者123 更新时间:2023-12-01 18:11:37 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Passing data between view controllers

(46 个回答)


7年前关闭。




我正在尝试将一个对象(PFObject)从一个 View Controller 传递给另一个,

-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
RestauCardViewController *restauCard = [[RestauCardViewController alloc]init];
RestaurantAnnotation *restoAnnotation = (RestaurantAnnotation *)view.annotation;

restauCard.restaurant = restoAnnotation.restaurant;
[self performSegueWithIdentifier:@"segueToCard" sender:nil];
}

当我尝试在另一个 View Controller 中显示对象时,我得到了 null:
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>

@interface RestauCardViewController : UIViewController

@property(nonatomic) PFObject *restaurant;

@end

这是我的 viewDidLoad 函数
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.

NSLog(@"The restaurant name is : %@",_restaurant[@"nom"]);
}

最佳答案

您需要使用 -prepareForSegue 来管理这种情况,并且您需要一个 iVar 来保留餐厅名称。

因此,在 map 的 .m 文件的顶部,添加一个 ivar NSString

@implementation yourViewController{

NSString *sRestName; //This is empty until the user selects a restaurant

}

-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
sRestName = //Set the name of your restaurent here, it's just a string.
//You could set any other type of object (a restaurent object or a PFOjbect or anything,
//just change the ivar accordingly
[self performSegueWithIdentifier:@"segueToCard" sender:nil];
}

你要做的就是用上面的代码替换你的旧代码,你只需要执行 segue 来调用下面的方法。
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 

if([segue.identifier isEqualToString:@"fromHomeToList"]){
RestauCardViewController *vc = (RestauCardViewController*)segue.destinationViewController;
vc.restaurant = sRestName; //here you're just giving the property of the new controller the content of your ivar.
}

这样,您就可以将 map 水龙头中的对象传递给您的下一个 Controller 。您还确定它永远不会为零,因为用户点击了它;如果它是零,那么,他一开始就不可能点击它!

请注意,我假设您使用字符串作为餐厅名称,但如果您更改顶部的 ivar,您可以使用任何您想要的内容, 只要您可以通过点击 map 检索它 .如果你不能,我需要更多细节来引导你完成另一个解决方案。

问我是否有任何问题,否则这应该有效!

关于ios - 在 View Controller 之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30048620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com