似乎没有通过引用传递

时间:2013-12-12 23:51:48

标签: ios objective-c pointers properties

我将UIView绘制代码放入方法中,作为我重构的一部分。看来这些观点 (属性)我传入方法不受任何方法的影响(即它们是零)。我需要改变什么?

示例摘录:

{
//...
[self plotLabelTextFieldSlider:_workEffortLabel label:_prewarnLabel textField:_prewarnTextField slider:_prewarnSlider labelText:@"Prewarn:"];
}

- (void)plotLabelTextFieldSlider:(UIView*)anchor label:(UILabel*)label textField:(UITextField*)textField slider:(UISlider*)slider labelText:(NSString*)labelText {

CGRect labelFrame = CGRectMake(anchor.frame.origin.x,anchor.frame.origin.y + anchor.frame.size.height + margin, anchor.frame.size.width, anchor.frame.size.height);
label = [[UILabel alloc] initWithFrame:labelFrame];
[self.view addSubview:label];
label.text = labelText;
//...
}

在上面的例子中,_prewarnLabel属性仍然是nil,当它在代码中的其他位置引用时,我已经通过方法的label参数设置了它。有人可以修复我的代码片段吗?

3 个答案:

答案 0 :(得分:0)

我假设您正在尝试使用行标签设置变量_prewarnLabel = [[UILabel alloc] ...如果这是您想要的,则需要更改参数以通过引用传递指针而不仅仅是通过通过引用的对象。

... label:(UILabel**)label ...

然后

... label:&_prewarnLabel ...

我强烈建议不要像这样编写代码。这令人困惑,难以理解。

答案 1 :(得分:0)

更好的方法是,由于您的方法创建了一个标签,您需要取回对新标签的引用,将执行以下操作:

- (UILabel *)plotLabelTextFieldSlider:(UIView*)anchor textField:(UITextField*)textField slider:(UISlider*)slider labelText:(NSString*)labelText {
    CGRect labelFrame = CGRectMake(anchor.frame.origin.x,anchor.frame.origin.y + anchor.frame.size.height + margin, anchor.frame.size.width, anchor.frame.size.height);
    UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
    [self.view addSubview:label];
    label.text = labelText;
    //...

    return label;
}

_prewarnLabel = [self plotLabelTextFieldSlider:_workEffortLabel textField:_prewarnTextField slider:_prewarnSlider labelText:@"Prewarn:"];

更新 - 实际上看起来这个方法可能需要创建几个视图并传回其中的几个。如果是这种情况,这将不起作用。

答案 2 :(得分:0)

正如其他人所说,C和目标C按值传递所有参数。它从未通过引用传递任何东西。获得该效果的唯一方法是将指针传递给指针,如Stephen Johnson的回答。这就是“(UILabel **)”构造正在做的事情。

当您将指针传递给指针时,您可以更改原始指针,从而改变您传入的变量。

相关问题