BACKGROUND:
I have a custom UIViewController class where I populate a MKMapView with custom annotations. When the user selects the annotation, details about that annotation are displayed, and a button is also present for the user to select and bring up another UIViewController with details about that point on the map.
The Code:
I initialize the new view controller by creating the class with a UserID (Note: - (id) initWithUserID:(NSInteger) userID; is declared in the header file of the SecondViewController:
@interface SecondViewController ()
@property (nonatomic) NSInteger userID;
@end
@implementation RainFallDetailedViewController
@synthesize userID = _userID;
- (id) initWithUserID:(NSInteger) userID{
_userID = userID;
NSLOG(@"UserID: %i",self.userID); //correctly displays user id
return self;
}
- (void) viewWillAppear{
NSLOG(@"UserID: %i",self.userID); //userid is now 0
Creating the view controller is done when the button is pressed, and then immediately performs the segue to the second view controller:
- (void)mapView:(MKMapView *)mapView
annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
if ([(UIButton*)control buttonType] == UIButtonTypeInfoLight){ //I'm looking for recognition of the correct button being pressed here.
//SecondViewController is the second view controller with the detailed information about the map point.
//DataPoint is a custom class that contains the details regarding the map point.
SecondViewController *detailedMapController = [[SecondViewController alloc] initWithUserID:((DataPoint *)view.annotation).userID];
NSLOG(@"UserID: %i", ((DataPoint *)view.annotation).userID); //correctly displays userID
[self performSegueWithIdentifier:@"PinDetail" sender:detailedMapController];
}
}
PROBLEM:
Using NSLOG I’m able to confirm that the value is being passed correctly when creating the class. However, when I go to use the property userID later on in the code (viewWillAppear), it’s not longer there for me to use. I’m assuming that there’s a memory issue that I’m not taking care of but I can’t seem to figure it out. How do I ensure that the values/object I pass into a class upon creation stay there?
Side Note: I originally tried, passing a PinData object, but ran into the same issue, so I know it’s not a NSInteger problem. I’ve also followed noa’s suggestion and used prepareForSegue however, I get the same problem presented above
The segue is responsible for instantiating the controller. Don’t instantiate another one – it’ll just be discarded, which is why the property values don’t seem to stick.
To set up the view controller, override
-prepareForSegue:instead, in the parent view controller:Replace the last block of code above with this: