How to access superclass variables in init method

Superclass Resource

 @interface Resource : CoderObject @property (strong, nonatomic) NSString *resourceID; @property (assign, nonatomic) ResourceType resourceType; @property (assign, nonatomic) DataType dataType; @end 

Subclass ViewResource

 @interface ViewResource : Resource @property (strong, nonatomic) CustomView *view; @property (strong, nonatomic) UIViewController *viewController; @end 

In a subclass of ViewResource init method of accessing the variable Resource dataType ? Now I'm trying to use super.dataType = ...

Are there any other ways?

0
ios objective-c
May 18 '13 at 9:37
source share
2 answers

You just need to use self.dataType . Your subclass has full visibility of all the properties of the superclass defined in the .h file. Using self.xxx also gives you the ability to redefine access methods if necessary in the future, without returning to edit all of your usage code.

Look at your link below, rightly. These are all valid points. Accessories should not have side effects, but you cannot guarantee that they will not. If a property is defined by a superclass, then you have several options:

  • Use self.xxx to set the property and try to ensure there are no side effects.
  • Call the init method on super, pass the necessary parameters and set there
+2
May 18 '13 at 9:39
source share

As Wayne said in his answer, you have direct access to your superclass members (if they are not private).

And there is no problem calling self.property in the init method if your init looks like this

 -(id)initAndTheNameYoWantAndMaybeSomeParameters:(NSString *)paramExample { self = [super initNameOfAnInitMethodFromSuperClass]; //check if the init was with success if(self != nil) { self.myStringProp = paramExample; //or self.propertyFromSuper = paramExample; } } 

Yes, you can also do stupid things in initMethods (I did this before :))), like calling the same initMethod from the inside, which generated a recursive call that crashed my application. (Easy to identify this problem)

0
May 18 '13 at 10:08
source share



All Articles