Best way to do init without repeating code?

Each view class has several init methods that are already included as part of the UIView, and then additional - and each of them sets the same elements in the same way. Therefore, I usually have everyone who has a method [self initialSetup];that involves setting up all of these elements.

The problem I ran into is that if the subclass also has an initialSetup method, it overrides the superclass initialSetup method, and thus the superclass must have an open public method in order to still function. This causes problems with the organization, since the method should never be called other than from init, so it has no reason to be public.

+5
source share
4 answers

You are faced with a problem in which there is no perfect solution. What you ideally have is a method that cannot be subclassed in the usual sense, available only to instances of this exact class type.

If this is a risk, it is common practice to include the class name in the installation method. So instead initialSetupyou will have something like myViewSubclassInitialSetup.

You can also add something like this at the top of your method:

NSAssert([self isMemberOfClass:[ThisClass class]], 
             @"IniitalSetup called by sub- or superclass")

Then your debug builds will throw an exception if a subclass or superclass ends with a call to the init method. This will give you room for a breakpoint and stacktrace, which should allow you to quickly find the problem.

It will not add any code to your versions.

+2
source

initialSetup initialSetupClassName - , , , .

"_" , , , , .

+2

, . , , . - , init, initWithName:, initWithName:age: initAsFiveYearOldNamed:, initWithName:age:, .

+2

Objective C "" . . Objective C

Apple , UIGestureRecognizer. , -, . , , (UIGestureRecognizerSubclass.h), UIGestureRecognizer "" . (.. ). . UIGestureRecognizer.

, - , , , . , "" , .

, , . , , . iOS Framework . F.E. UIViewController viewDidLoad ..

+1

All Articles