-->

Pass NSString between two DetailViewController

2019-09-21 11:01发布

问题:

MasterViewController.m

#import "DetailViewController.h"

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
    if ([segue.identifier isEqualToString:@"DetailViewControllerSeque"]) {
        DetailViewController *detailView = [segue destinationViewController];

        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];

        theList = [app.listArray objectAtIndex:indexPath.row];

        detailView.theList = theList;

        // String to pass to DetailViewController
        detailView.string2pass = @"this is a passing string";
    }
}


DetailViewController.h

NSString *string2pass;

@property (retain, nonatomic) NSString *string2pass;


DetailViewController.m

NSLog(@"%@", string2pass);

Output: (null)


What I am doing wrong?

回答1:

Unless you have this in your implementation, it won't work as you expected.

@synthesize string2pass = string2pass;

..or you can fix it by deleting the line:

NSString *string2pass;

Your log is logging the value of string2pass variable you declared. But there is another variable _string2pass.

NSLog(@"%@", string2pass);

The @property you declared, is backed by a variable name _string2pass if you don't explicitly write a @synthesize statement. Not writing an @sythesize statement is the same as declaring one like so:

@synthesize string2pass = _string2pass;


回答2:

Use self.string2pass in NSLog. When we use self. to access a property then the getter/setter is called.



回答3:

In your DetailViewController.h only you need to define this -

@property (strong, nonatomic) NSString *string2pass;

In your DetailViewController.m

@synthesize string2pass 

This will work for you.



回答4:

First you need to add NSString property to your SecondViewController.h file:

@property (nonatomic, copy) NSString *myString;

and then in FirstViewController.m file create SecondViewController object and pass to it whatever string you want:

SecondViewController *secondViewcontroller = [[SecondViewController alloc] initWithNibName:@"ACEViewController" bundle:nil];
secondViewcontroller.myString = @"WhateverYouNeedToPass";

Log string in SecondViewController

NSLog(@"%@", self.myString);