【问题标题】:Custom init or public properties What is the best way to send parameters between viewControllers自定义初始化或公共属性在viewControllers之间发送参数的最佳方式是什么
【发布时间】:2014-02-21 15:56:53
【问题描述】:

我想知道哪个是在 viewController 之间发送参数的最佳方式。我知道有两种可能,在init调用之后传递公共属性中的参数。

ViewController *vc = [ViewController alloc] init];
vc.propertyOne = @"whatever";
vc.propertyTwo = @"whatever2";

或创建一个新的自定义初始化,如

initWithProperty:(NSString *)prperty1 andPropertyTwo:(NSString *)property2 
{
  self = [super init];
    if (self) {
        self.propertyOne = prperty1;
        self.propertyTwo = property2;
    }
    return self;

}

ViewController *vc = [[ViewController alloc] initWithProperty:@"whatever andPropertyTwo:@"xxxx"];

我想知道每一种的优缺点,“何时”和“为什么”最好使用其中一种。

【问题讨论】:

标签: ios objective-c uiviewcontroller init


【解决方案1】:

如果在实现init 方法时立即需要这些值,您应该将参数传递给自定义init 方法。

如果您要设置多个属性并且init 方法本身不需要这些属性,则应该使用在调用alloc/init 之后设置的属性。

很多时候直到viewDidLoad(在视图控制器的情况下)才需要属性,所以使用属性更简洁。您不想以带有十几个参数的init 方法结束。

【讨论】:

  • 谢谢。我已经看到了两种方式,但我不明白为什么。现在,我明白了。
猜你喜欢
  • 2011-05-10
  • 2010-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-17
  • 2019-08-03
  • 1970-01-01
相关资源
最近更新 更多