2

In objective c, should I overwrite the init method to initialize my variables? If the variables are properties can I still access them the usual way to set their initial value?

Nosrettap
  • 10,940
  • 23
  • 85
  • 140
  • 1
    You should overRIDE the `init` method with your own (if you use `init`), but always call the `super` version before the body of your own. You can initialize variables in viewDidLoad if you are writing a view controller. When you initialize variables may (or may not) be important. – Hot Licks May 22 '12 at 15:01

4 Answers4

3

In objective c, should I overwrite the init method to initialize my variables?

Yes. Specifically, the designated initializer(s).

Your subclass may also specify another construction stage (e.g. viewDidLoad). Also, the object's memory is zeroed when it is allocated, so you do not need to set them explicitly to 0/nil (unless you find it more readable).

If the variables are properties can I still access them the usual way to set their initial value?

You should avoid using the object's instance methods/accessors, and access ivars directly in partially constructed states (notably the initializer and dealloc). There are a number of side effects you will want to avoid - Example Here;

Community
  • 1
  • 1
justin
  • 104,054
  • 14
  • 179
  • 226
1

you can initialize you variables in viewDidLoad method of a view controller.

Anila
  • 1,136
  • 2
  • 18
  • 42
1

Variables declared in the classes interface will automatically be initialized to there default value, 0 for integral values and nil/NULL for classes and pointers. If you need to initialize the variables to other values then you need to override a guaranteed entry point for you class. A custom class inheriting from NSObject for example you will simply override init. If you are working with a view controller loaded from a NIB file then you could override initWithCoder: or – awakeFromNib. You should always check the documentation for whichever class you are inheriting from and find the designated initializer for that class. Sometimes you will need to set a common initializing method and call it from various initializers. Also if you have a variable that is also a property it is recommended that you should set the property and not the variable directly.

Joe
  • 56,979
  • 9
  • 128
  • 135
  • Also if you have a variable that is also a property it is recommended that you should set the property and not the variable directly. Why ?? – onmyway133 Oct 22 '13 at 17:05
0

should I overwrite the init method to initialize my variables?

Instance variables: yes, although they are by default initialised to 0/nil/false already.

If the variables are properties can I still access them the usual way to set their initial value?

Yes you can. Apple advises against it because of the danger that a subclass has overridden the set accessor to do something unexpected. In practice, this is rarely a problem.

JeremyP
  • 84,577
  • 15
  • 123
  • 161