Search code examples
objective-cparameter-passinguistoryboardsegue

segue data passing returns nil


I need to pass a NSString to my other ViewController but it keeps returning nil.

//prepareForSegue is called from didSelectRowAtIndexPath
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if([[segue identifier] isEqualToString:@"chat"]) {
        NSString *userName = (NSString *) [toUsersArray objectAtIndex:[self.chatsTableView indexPathForSelectedRow].row];

        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];

    ChatViewController *chatViewController = [storyboard instantiateViewControllerWithIdentifier:@"ChatViewController"];
    //[chatViewController setChatWithUser:userName]; EVEN TRIED:
    chatViewController.chatWithUser = username;
    }

}

Here is where I declare the NSString:

@interface ChatViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, MessageDelegate> {
UITextField     *messageField;
NSString        *chatWithUser;
UITableView     *chatTableView;
NSMutableArray  *messagesArray;
}

@property (nonatomic,retain) IBOutlet UITextField *messageField;
@property (nonatomic,retain) NSString *chatWithUser;
@property (nonatomic,retain) IBOutlet UITableView *chatTableView;

- (IBAction) sendMessage;

@end

and here its still nil:

 @synthesize chatWithUser;
    - (void)viewDidLoad {
        [super viewDidLoad];
        //DO STUFF WITH chatWithUser; ADDED BREAKPOINT AND chatWithUser = nil;
        //ALSO TRIED viewWillAppear;
    }

What is the right way to pass data between these two View Controllers? My variables stay nil.


Solution

  • The problem is that you're instantiating a new ChatViewController, that's not the one that the segue is going to. You should get that controller from the segue's destinationViewController property.

    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
        if([[segue identifier] isEqualToString:@"chat"]) {
            NSString *userName = (NSString *) [toUsersArray objectAtIndex:[self.chatsTableView indexPathForSelectedRow].row];
    
        ChatViewController *chatViewController = segue.destinationViewController;
        chatViewController.chatWithUser = username;
        }
    }