简体   繁体   中英

Passing variable to another view controller using instantiateViewControllerWithIdentifier

.m file from which I'm trying to set the message variable:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SingleMessageViewController* vc = (SingleMessageViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"SingleMessageViewController"];
    vc.message = [tableView cellForRowAtIndexPath:indexPath].textLabel.text;
    [self.navigationController pushViewController:vc animated:true];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

.h file of the view controller I'm instantiating:

@interface SingleMessageViewController : POSCommonViewController
{
    NSString *message;
}

@property (nonatomic, retain) NSString *message;
@end

.m file of the view controller I'm instantiating ( viewDidLoad method only):

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"%@", self.message);
}

NSLog in the last file quoted returns nil (view loads without any problems). I've tried changing the properties, etc. - nothing worked for me. What could be the problem here?

The textLabel property of the selected cell could be nil. Use an intermediate string variable to get the cell's text and then set the message to that. It'll make it easier to see the message when you step through the first method in the debugger.

No its not work .You are creating the object of the controller inside the first controller and setting the property for that particular object . Then how you can access this inside the new controllers object ? To achieve this you can use the following ways:

1.you can override the init method in the second view controller that is initWithMessage:(NSString *)message

2.You can add the property inside the appDelegate class. That will be shared through the application .

3.But best way is to make a singleton class if you want to share anything within the classes .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM