【问题标题】:In Objective-C, is it possible to set default value for a class variable?在 Objective-C 中,是否可以为类变量设置默认值?
【发布时间】:2011-03-17 21:09:42
【问题描述】:

有没有办法为类的类属性设置默认值? 就像我们在 Java 中可以做的那样,在类的构造函数中,例如。-

MyClass(int a, String str){//constructor
  this.a = a;
  this.str = str;
  
  // I am loking for similar way in Obj-C as follows 
  this.x = a*5;
  this.y = 'nothing';
}

我为什么要寻找:

我有一个包含大约 15 个属性的类。当我实例化类时,我必须为所有这些变量/属性设置一些默认值。因此,这使我的代码既繁重又复杂。如果我可以从该类中为这些实例变量设置一些默认值,那必须降低此代码的复杂性/冗余。

【问题讨论】:

  • “类变量”是指“实例变量”(ivar)吗?
  • 抱歉没有说清楚。是的,它的实例变量

标签: objective-c default-value class-variables


【解决方案1】:

如果你不想指定参数,

- (MyClass *)init {
    if (self = [super init]) {
        a = 4;
        str = @"test";
    }
    return self;
}

然后当您执行MyClass *instance = [[MyClass alloc] init] 时,它会为 ivars 设置默认值。

但我不明白为什么你发布了带有参数的构造函数,但你不想使用它们。

【讨论】:

    【解决方案2】:

    编写 init,它负责完全初始化的所有工作。

    然后根据需要编写尽可能多的具有不同参数集的启动器(但请考虑一下:您真的需要 thisthat 一个吗?)。不,不要让他们做这项工作。让他们填写所有默认值(您不提供给 message 的那些,给 this 消息处理实现)并将其全部提供给第一个。

    第一个启动器称为指定启动器。 千万不要错过Multiple Initializers and the Designated Initializer. 永远不要忽略指定的!

    问候

    【讨论】:

      【解决方案3】:

      在类的界面中:

      @interface YourClass : NSObject {
          NSInteger a;
          NSInteger x;
          NSString  *str;
          NSString  *y;
      }
      
      - (id)initWithInteger:(NSInteger)someInteger string:(NSString *)someString;
      
      @end
      

      那么,在实现中:

      - (id)initWithInteger:(NSInteger)someInteger string:(NSString *)someString {
          if (self = [super init]) {
              a = someInteger;
              str = [someString copy];
      
              x = a * 5;
              y = [@"nothing" retain];
          }
      
          return self;
      }
      

      NSIntegerintlong 的 typedef,具体取决于架构。)

      【讨论】:

      • 感谢@wevan。我仍然必须向初始化方法发送一些参数。有没有任何方法可以在没有任何参数的情况下使用 init{} 或类似的东西?
      猜你喜欢
      • 2010-12-19
      • 2019-08-24
      • 2014-10-15
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多