在 Objective-C 中,是否可以为类变量设置默认值?
有没有办法为类的类属性设置默认值? 就像我们在 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 个属性的类。当我实例化该类时,我必须使用一些默认值设置所有这些变量/属性。所以这使得我的代码既沉重又复杂。如果我可以为该类中的这些实例变量设置一些默认值,那么一定会降低代码的复杂性/冗余。
Is there any way to set default values for class properties of a class?
Like what we can do in Java, in the constructor of the class eg.-
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';
}
Why I am looking for:
I have a class with about 15 properties. When I instantiate the class, I have to set all those variable/properties with some default values. So this makes my code heavy as well complex. If I could set some default values to those instance variables from within that class, that must reduce this code complexity/redundancy.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您不想指定参数,
那么当您执行
MyClass *instance = [[MyClass alloc] init]
时,它将设置 ivars 的默认值。但我不明白为什么你发布了带有参数的构造函数但你不想使用它们。
If you don't wanna specify parameters,
Then when you do
MyClass *instance = [[MyClass alloc] init]
, it'll set the default values for the ivars.But I don't see why you posted the constructor with parameters but you don't want to use them.
编写init,它完成完全初始化的所有工作。
然后根据需要编写尽可能多的具有不同参数集的启动器(但想一想:您真的需要这个或那个吗?)。不,不要让他们做这项工作。让他们填写所有默认值(您没有提供给消息、此消息处理实现的默认值)并将其全部交给第一个。
第一个发起者称为指定发起者。 并且一定不要错过多个初始化器和指定初始化器。
绝不忽略指定的人!
问候
Write the init, which is doing all the job of full initialization.
Then just write as many initiators with diferent parameter sets as you need (but think about it: do you really need this or that one?). No, don’t let them do the job. Do them let fill in all the default values (the ones you don’t provide to the message, to this message handling implementatino) and give it all to the first one.
This first one initator is called designated initator. And be sure not to miss Multiple Initializers and the Designated Initializer.
Never ignore the designated one!
Greetings
在类的接口中:
然后,在实现中:(
NSInteger
是int
或long
的 typedef,具体取决于架构。)In the class's interface:
Then, in the implementation:
(
NSInteger
is a typedef forint
orlong
, depending on the architecture.)