Objective c segue数据传递返回nil
我需要将NSString传递给另一个ViewController,但它始终返回nilObjective c segue数据传递返回nil,objective-c,parameter-passing,uistoryboardsegue,Objective C,Parameter Passing,Uistoryboardsegue,我需要将NSString传递给另一个ViewController,但它始终返回nil //prepareForSegue is called from didSelectRowAtIndexPath - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if([[segue identifier] isEqualToString:@"chat"]) { NSString *userNa
//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;
}
}
下面是我声明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
在这两个视图控制器之间传递数据的正确方式是什么?我的变量保持为零。问题是您正在实例化一个新的ChatViewController,而这不是segue将要使用的。您应该从segue的destinationViewController属性获取该控制器
- (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;
}
}
问题是您正在实例化一个新的ChatViewController,而这不是segue将要使用的。您应该从segue的destinationViewController属性获取该控制器
- (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;
}
}
//获取对目标视图控制器的引用
ChatViewController*ChatViewController=[segue destinationViewController] //获取对目标视图控制器的引用 ChatViewController*ChatViewController=[segue destinationViewController]