Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Objective-C中,是否可以为类变量设置默认值?_Objective C_Default Value_Class Variables - Fatal编程技术网

在Objective-C中,是否可以为类变量设置默认值?

在Objective-C中,是否可以为类变量设置默认值?,objective-c,default-value,class-variables,Objective C,Default Value,Class Variables,有没有办法为类的类属性设置默认值? 就像我们在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个属性的类。当我实例化这个类时,

有没有办法为类的类属性设置默认值? 就像我们在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个属性的类。当我实例化这个类时,我必须用一些默认值设置所有这些变量/属性。因此,这使得我的代码既繁重又复杂。如果我可以在该类中为这些实例变量设置一些默认值,则必须降低代码复杂性/冗余。

在该类的接口中:

@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;
}

NSInteger
int
long
的类型定义,具体取决于体系结构。)

如果不想指定参数

- (MyClass *)init {
    if (self = [super init]) {
        a = 4;
        str = @"test";
    }
    return self;
}
然后,当您执行
MyClass*instance=[[MyClass alloc]init]
时,它将为IVAR设置默认值

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

编写init,它完成了全部初始化工作

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

第一个启动器称为指定启动器并确保不要错过 永远不要忽视指定的一个


问候语

所说的“类变量”是指“实例变量”(ivar)吗?很抱歉没有明确提及。是的,它的实例可变谢谢@wevan。我仍然需要向初始化方法发送一些参数。有没有办法在没有任何参数的情况下使用init{}或类似的东西?