Objective-C set default value for a property

前端 未结 7 629
感情败类
感情败类 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:23

    I have never seen this behavior before but I'm pretty sure this is what the init step is for when allocation an object, that is setting variables and initializing the object.

    -(id)init {
         if (self = [super init])  {
           self.someProperty = 10;
         }
         return self;
    }
    

    And the call it like this:

    MyClass* test = [[MyClass alloc] init];
    

    Notice that you can have more than one init function which allows you to have a few different sets of default values.

    What @synthesize does is tell the precompiler that it should generate the code for the set/get, not set the value of the property. The '=" just tells the precomplier that, even though the name of the variable and the property are not the same, they should be connected.

    Also, as a personal opinion (not realated to the question at all), this object seems way to big and you might be able to split it up in some way or do like other person suggested. Maybe this class could inherit from a few other classes to give it the different properties it needs? As I said, it just a suggestion since I don't know what your other code looks like :)

提交回复
热议问题