通过accessoryButton将字符串传递给不同的视图控制器返回null

时间:2014-08-08 22:24:04

标签: ios string uiviewcontroller storyboard

我有一个UITableViewController“FirstViewController”和带有附件视图按钮的单元格。我正在使用accessoryButtonTappedForRowWithIndexPath委托方法在选择行时设置一些字符串值。然后有一个故事板转换到新的UIViewController,我试图将此字符串设置为UILabel的文本。但是在新视图控制器中,字符串返回null,不会保留。第二个视图控制器是在故事板中设计的。我有什么想法吗?

FirstViewController.h

@property (strong, nonatomic) IBOutlet UILabel *titlelbl;
@property (nonatomic, strong) NSString * atitle;

FirstViewController.m

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    self.atitle = [[NSString alloc] initWithString:[alltitles objectAtIndex:[indexPath row] - 1]]; // this string returns a proper value
    NSLog(@"%@", self.atitle);

    NSString * storyboardName = @"MainStoryboard";
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil];
    UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"articles"];
    vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:vc animated:YES completion:nil];
}

SecondViewController.m

#import "SecondViewController.h"
#import "FirstViewController.h"

@synthesize atitle;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    FirstViewController * irstViewController = [[FirstViewController alloc] init];
    firstViewController.atitle = self.atitle;  // the string returns null. it does not retain the value from the first view controller
    self.titlelbl.text = self.atitle;
    self.sourcelbl.text = @"Source:";
    NSLog(@"%@", self.atitle);
}

1 个答案:

答案 0 :(得分:1)

您的FirstViewController正在设置param值:

self.atitle = [[NSString alloc] initWithString:[alltitles objectAtIndex:[indexPath row] - 1]]; // this string returns a proper value

您的SecondViewController似乎从自身读取相同的值..

firstViewController.atitle = self.atitle;  // the string returns null. it does not retain the value from the first view controller

当你分配一个新的FirstViewController时。您正在查看一个全新的对象,因此该对象上的标题与新对象的标题不同。

您必须在secondviewcontroller上设置aTitle。

在这种情况下也建议使用segues。