【问题标题】:Pass NSString between two DetailViewController在两个 DetailViewController 之间传递 NSString
【发布时间】:2013-09-16 12:36:40
【问题描述】:

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);

输出:(空)


我做错了什么?

【问题讨论】:

  • 你是从哪里调用 NSLog 的?
  • 你合成了那个属性吗?一旦你可以在分配之前为 detailView.string2pass 打印 NSLog..
  • 我觉得这个更详细试试这个stackoverflow.com/questions/5210535/…
  • 是的,我在我的问题中更正了它
  • 你确定 detailView 不是 nil 吗? NSLog(@"%@", detailView) 从 segue 中获取后。

标签: ios objective-c nsstring


【解决方案1】:

除非你在你的实现中有这个,否则它不会像你预期的那样工作。

@synthesize string2pass = string2pass;

..或者您可以通过删除该行来修复它:

NSString *string2pass;

您的日志正在记录您声明的 string2pass 变量的值。但是还有另一个变量_string2pass。

NSLog(@"%@", string2pass);

如果您没有明确编写@synthesize 语句,则您声明的@property 由变量名_string2pass 支持。不写@sythesize 语句与声明这样的语句相同:

@synthesize string2pass = _string2pass;

【讨论】:

  • 感谢您的帮助,但即使我删除 NSString *string2pass; 并添加 @synthesize string2pass = _string2pass; 我仍然得到(空):(
  • 如果您不想要,实际上不需要显式编写该综合语句,它的存在并没有什么坏处 - 但如果您不编写它,它是为您创建的。如果你这样做了,那么你现在可能不会在不将 NSLog 语句更改为读取 NSLog(@"%@", self.string2pass).... 的情况下进行编译。你这样做了吗?另外,你从哪里调用 NSLog 语句?
  • 从 viewDidLoad 调用。是的,我也尝试过不带@sythesize 和 self.string2pass,但也没有工作......
  • 我不使用故事板,所以我不太确定生命周期 - 在设置变量之前是否调用了 viewDidLoad?如果您从 viewWillAppear 登录会怎样?
【解决方案2】:

NSLog 中使用self.string2pass。当我们使用 self.要访问一个属性,然后调用 getter/setter。

【讨论】:

  • 请给出反对的理由?
  • ...不是我...但是,我认为您被否决了,因为您的回答隐藏了真正的问题,即有 2 个变量,这可能会导致更多的错误/混乱行。
  • 是的,我同意它不包括整个场景,但这不是一个错误的答案。无论如何,您已经完全回答了上面的问题,因此再次重复这些事情没有任何意义。
  • 从技术上讲,您是正确的。我认为它不值得投反对票。
【解决方案3】:

在你的 DetailViewController.h 中你只需要定义这个 -

@property (strong, nonatomic) NSString *string2pass;

在您的 DetailViewController.m

@synthesize string2pass 

这对你有用。

【讨论】:

  • 仍然得到 (null) :(
【解决方案4】:

首先您需要将NSString 属性添加到您的SecondViewController.h 文件中:

@property (nonatomic, copy) NSString *myString;

然后在FirstViewController.m 文件中创建SecondViewController 对象并将您想要的任何字符串传递给它:

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

SecondViewController中的日志字符串

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-14
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 2022-01-01
    相关资源
    最近更新 更多