Objective-c using parent properties in init method

I read that using properties in the init method is considered bad practice. But should you use the properties of the parent class?

for instance

 -(id) init { if (self = [super init]) { self.parentProp = someVal; // (1) parentProp = someVal; // (2) } return self; } 

Which is preferable (1 or 2) and why? Thanks!

+4
source share
2 answers

After you call the super init method and it returns, part of the superclass of your object is initialized and ready for use. This is normal and you are expected to use your property accessors after that. For instance. If you create a subclass of UIViewController , then you will normally be given your (inherited) title property or change your navigationItem in the init method.

However, you may violate this behavior. If you override one of your superclass methods (including one of its access methods) and then you call this method in the init method, you need to make sure that your overridden method will behave correctly before your object is fully initialized.

More subtly, you may have redefined the superclass method, and then you will call another method of the superclass that you have not redefined. Well, what if the method you invoke wraps around and invokes the method that you redefined? You should also be aware of this feature.

All that has been said, I repeat that it is perfectly normal to use your superclass property accessors to configure it after you initialize it by calling one of its init methods.

+3
source

To answer your question - not one of them.

  • (2) This is not access to properties, but direct access to an instance variable. It depends on the design of the class hierarchy, but on the whole I would strongly refuse to use ivars in non-personal interfaces - see this answer to the corresponding question for details
  • In the general case, you should not use any public methods of the class (including access to properties) in the class initializer (in this case dealloc) - unless the class hierarchy explicitly prohibits subclasses. Because if you do this, subclasses that override these methods (or property accessories) will receive them called when they are in an invalid state (not yet initialized or already freed).

While I ran into a number of problems caused by pt.2 in general, it seems that it is common practice to ignore it (for example, use the self / parent class properties in the initializer). So I would say that to you. Or write more code to explicitly configure outside of class initializers, and make sure you never run into this problem. Or perhaps a simpler / shorter initialization and simpler use of your class, but don't forget about this problem.

+1
source

All Articles