When I am trying to set a property from destination controller within prepareSegue method, it is possible for some types of properties, while some others are not. For example, let’s say my destination controller contains the following properties:
@interface MapController:UIViewController
@property (weak, nonatomic) IBOutlet UIWebView *streetView;
@property (strong, nonatomic) NSString *url;
@property (nonatomic) NSString *latitude;
@property (nonatomic) NSString *longitude;
@property (nonatomic) Venue *venue;
@end
By the way, “Venue” looks like this:
@interface Venue:NSObject
@property (nonatomic) NSString *latitude;
@property (nonatomic) NSString *longitude;
@end
The following code works:
/****** CODE 1 *******/
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([[segue identifier] isEqualToString:@"MapViewSegue"]){
MapController *cvc =
(MapController *)[segue destinationViewController];
NSIndexPath *selectedIndex = self.tableView.indexPathForSelectedRow;
Venue *v = (Venue *)[self.entries objectAtIndex:[selectedIndex row]];
/****** Note the difference from CODE 2 below! ******/
cvc.latitude = v.latitude;
cvc.longitude = v.longitude;
// At this point,
// both cvc.latitude and cvc.longitude are properly set.
}
}
But this one doesn’t work:
/****** CODE 2 *******/
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([[segue identifier] isEqualToString:@"MapViewSegue"]){
MapController *cvc =
(MapController *)[segue destinationViewController];
NSIndexPath *selectedIndex = self.tableView.indexPathForSelectedRow;
Venue *v = (Venue *)[self.entries objectAtIndex:[selectedIndex row]];
/****** Note the difference from CODE 1 above! ******/
cvc.venue.latitude = v.latitude;
cvc.venue.longitude = v.longitude;
// At this point,
// both cvc.venue.latitude and cvc.venue.longitude are nil
}
}
As I noted in the code, it seems that an NSString property can be set within prepareSegue, but if I try to instantiate my own object it ends up with nil. I was wondering why this is happening. Thank you in advance!
The second code doesn’t work because cvc.venue doesn’t point to anything — you haven’t instantiated a venue object in your MapController class. There’s nothing special about your custom object, it’s no different than if you had: @property (nonatomic) NSArray *array; — array will be nil until you instantiate a new array object.