segue数据传递返回nil

时间:2013-09-02 16:13:10

标签: 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 *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

这里还是零:

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

在这两个View Controller之间传递数据的正确方法是什么?我的变量保持无效。

2 个答案:

答案 0 :(得分:2)

问题是你正在实例化一个新的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;
    }
}

答案 1 :(得分:1)

//获取对目标视图控制器的引用

ChatViewController * ChatViewController = [segue destinationViewController];

相关问题