Jung Kang Yu
Jung Kang Yu

Reputation: 1

How can I share the variable for mapkit between two viewcontroller?

I want to show the pin annotation on the new view controller when the "map" button is clicked on the upper level view controller.

So I used the "IBAction" method on the method file of the upper level controller as below. Then the latitude and longitude values appeared normally (in the NSLog) from the property list. But I can't see the pin annotation on the new view controller.

However, if I put the code marked "code for viewDidLoad" on the new view controller (named "location") then I can see the pin annotation. But the latitude and longitude value is only 0.00000.

I think the variable isn't shared between two view controller. Please help me to solve this problem.

- (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];

Upvotes: 0

Views: 105

Answers (1)

user467105
user467105

Reputation:

I assume the variable you want to share is drink. If you've just declared drink as an ivar in both view controllers, that won't "share" it automatically. After you alloc+init location in goAddView, drink will be nil in lm. The viewDidLoad method in location will get called when you push/present it.

One way to pass the value to location is using properties. First, declare drink as a property in the location view controller:

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

Next, set the property after you alloc+init it in goAddView and before you call 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
}

Upvotes: 1

Related Questions