ios - 如何在两个 View Controller 之间共享mapkit的变量?

标签 ios uiviewcontroller

当单击上层 View Controller 上的“ map ”按钮时,我想在新 View Controller 上显示引脚注释。

所以我在上层 Controller 的方法文件中使用了“IBAction”方法,如下所示。 然后,纬度和经度值会从属性列表中正常显示(在 NSLog 中)。 但我在新 View Controller 上看不到引脚注释。

但是,如果我将标记为“viewDidLoad 的代码”的代码放在新 View Controller (名为“位置”)上,那么我可以看到引脚注释。 但经纬度值只有0.00000。

我认为该变量不在两个 View Controller 之间共享。 请帮我解决这个问题。

- (IBAction) goAddView:(id)sender {

// the code for viewDidLoad  
    double myLat = [[drink objectForKey:lati_KEY] doubleValue];
    double myLong = [[drink objectForKey:long_KEY] doubleValue];                CLLocationCoordinate2D theCoordinate;
     theCoordinate.latitude =  myLat;
     theCoordinate.longitude = myLong;
     NSLog(@"the latitude = %f",theCoordinate.latitude);
     NSLog(@"the longitude = %f",theCoordinate.longitude);

     myAnnotation *myAnnotation1=[[myAnnotation alloc] init];

     myAnnotation1.coordinate=theCoordinate;
     myAnnotation1.title=@"Destination";
     myAnnotation1.subtitle=@"in the city";
     [self.mapView addAnnotation:myAnnotation1]; 
// the code end

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

最佳答案

我假设您要共享的变量是drink。如果您刚刚在两个 View Controller 中将 drink 声明为 ivar,则不会自动“共享”它。在goAddView中alloc+init location后,drinklm中将为nil 。当您推送/呈现它时,将调用 location 中的 viewDidLoad 方法。

将值传递给位置的一种方法是使用属性。首先,将 drink 声明为 location View Controller 中的属性:

//in location.h:
@property (retain) NSDictionary *drink;
//in location.m:
@synthesize drink;
//and release in dealloc if not using ARC

接下来,在 goAddView 中分配+初始化该属性之后以及调用 pushViewController之前设置该属性:

- (IBAction) goAddView:(id)sender 
{
    location *lm = [[location alloc] initWithNibName:@"location" bundle:nil];

    lm.drink = drink;  //point drink in lm to the one in current vc

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

    //and do [lm release]; if not using ARC
}

关于ios - 如何在两个 View Controller 之间共享mapkit的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8670220/

相关文章:

iphone - 接收器(<ViewController :>) has no segue with identifier - initiating segue from a scene

iphone - 将数据传回前一个 View Controller

iphone - 从多个表中过滤数据

ios - 如何在 Xcode Storyboard 中平均分配项目空间?

ios - 使用 Swift 以编程方式更改 UIButton 的大小

ios6 autorotation portraitupsidedown 到 portrait

ios - 在另一个 View Controller 中添加一个 View Controller 作为 subview

ios - 未出现的 View Controller

ios - 在 viewDidLoad 中调用时 Firebase 观察者未观察到数据库更改

ios - 在 UICollectionViewController 上呈现 ActionSheet 警报