Objective-C set default value for a property

前端 未结 7 624
感情败类
感情败类 2021-02-03 20:30

I\'m making an app, and I have a class with quite a lot properties and I was wondering if it was possible to give them a default value. Because if I make an init method, it\'s a

7条回答
  •  情话喂你
    2021-02-03 21:13

    There is no built-in Java-like way of initializing synthesized properties or ivars in Objective C. However, since your properties look almost identical, you might want to consider making them @dynamic instead of synthesizing them.

    For sure, you would need to write two scary-looking methods (here is a nice and clean example for you), but in return you get a uniform way of storing your properties as objects inside NSMutableDictionary. This opens up several interesting alternatives not available with plain ivars: you could defer initialization of your properties until they are needed, you could provide default values for unset properties, or you could initialize your properties "wholesale" by filling in the dictionary with values for their keys.

提交回复
热议问题