【问题标题】:Can't set property in prepareForSegue:sender:无法在 prepareForSegue:sender 中设置属性:
【发布时间】:2012-02-29 04:58:46
【问题描述】:

下面的解决方案 - 并不是我认为的问题。

我正在使用 prepareForSegue:sender: 将数据添加到正在被插入的视图控制器,但我的问题是,如果使用属性设置数据,则该属性不会更改。但是,我可以使用目标视图控制器的私有变量,使用为此目的构建的函数进行设置。

这是有效的代码:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"showLocationDetail"]) {
        CityGuideFlipsideViewController *flipside = [segue destinationViewController];
        CityGuideAnnotation *senderAnnotation = (CityGuideAnnotation *)sender;
        [flipside annotate:senderAnnotation]; // why?
    } 
}

不过,使用flipside.annotate = senderAnnotation 似乎比使用[flipside annotate:senderAnnotation] 更自然。

我肯定在这里做了一些明显的事情,但我无法发现它。

编辑以更清楚地给出失败案例:

// CityGuideFlipsideViewController.h
@interface CityGuideFlipsideViewController : UIViewController {
    CityGuideAnnotation *annotation;
}
@property (strong, nonatomic) CityGuideAnnotation *annotation;

// CityGuideFlipsideViewController.m
@synthesize annotation;
- (void)setAnnotation:(CityGuideAnnotation *)_annotation
{
    annotation = _annotation;
}

// CityGuideMainViewController.m (in prepareForSegue:sender)
CityGuideFlipsideViewController *flipside = [segue destinationViewController];
CityGuideAnnotation *senderAnnotation = (CityGuideAnnotation *)sender;
flipside.annotation = senderAnnotation;

到达将flipside.annotation 指定为senderAnnotation 的行时,senderAnnotation 的值是正确的。赋值前的flipside.annotation 为nil。在该行之后 senderAnnotation 不变,flipside.annotation 不变。

但是,到达 CityGuideFlipsideViewController viewDidLoad 我有 NSLog(@"%@",annotation.title) 吐出正确的值,即使调试器仍然显示我的注释为零。

所以我真的不确定我之前是否有一些小错误,如果我一直被调试器中的annotation CityGuideAnnotation * 0x00000000 愚弄。

对此感到抱歉,感谢帮助过的人。

【问题讨论】:

  • 有没有可能,您之前没有正确或根本没有正确地投射您的发件人。我注意到您在成功的代码中将其转换为 CityGuideAnnotation,但在示例中却没有。
  • 请给出annotate的声明和实现。属性用于设置ivars,与x.annotate = y等效的setter方法应该是[x setAnnotate:y]

标签: objective-c ios storyboard segue


【解决方案1】:

如果 annotation 是目标 vc 上的私有属性,则发送方 VC 无法访问它(除了您设置的 annotate: 方法)。 prepareForSegue 没有对destinationVC 提供任何特殊访问权限,在本例中是私有属性。如果您想使用点表示法,您需要将 annotate 作为公共 API 的一部分公开。

我希望我能正确理解你的问题:-)

祝你好运,

达米安

【讨论】:

  • 不幸的是它不是私人的。编译器也没有抛出错误,只是未设置 Flipside.annotation。
  • 它是一个 UI 插座吗?在 prepareForSegue 期间,出口未连接到目标 vc。
  • 感谢 Damien 的帮助,抱歉我没有早点弄清楚调试器的问题。
【解决方案2】:

错误不在使用属性的代码中。我被显示 nil 作为指针的调试器愚弄了。以后我会更加小心地记录值。

有关详细信息,请参阅上述问题的编辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-17
    • 1970-01-01
    • 2015-02-08
    • 1970-01-01
    相关资源
    最近更新 更多