Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to do init without repeating code?

Each view class has multiple init methods - ones already included as part of UIView, and then additional ones - and each of them set up the same elements in the same way. I therefore usually have them all running a [self initialSetup]; method, which includes the setting up of all of these elements.

The problem i've ran into is that if a subclass also has an initialSetup method, it would override the superclass initialSetup method, and thus the superclass would have to have the method be public in order to still function. This causes problems with organisation, as the method should never be called other than from init, so has no reason to be public.

like image 956
Andrew Avatar asked Apr 12 '13 22:04

Andrew


2 Answers

You've hit upon a problem that there's no perfect fix for. What you'd ideally have is a method that can't be subclassed in the normal sense, that's accessible only to instances of that exact type of class.

Where this is a risk, the normal practice seems to be to incorporate the class name into the setup method. So instead of initialSetup you'd 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 raise an exception if a subclass or superclass ends up calling your init method. That'll give you a place for a breakpoint and a stacktrace that should allow you to find the problem very quickly.

It won't add any code to your release builds.

like image 185
Tommy Avatar answered Oct 08 '22 06:10

Tommy


Change the name of initialSetup to something like initialSetupClassName - subclasses, even if they accidentally used the same pattern, would not use the same name as they had a different class name.

You can also use an "_" prefix for private methods you would rather not be called, but the subclasser may do that also.

like image 37
Kendall Helmstetter Gelner Avatar answered Oct 08 '22 08:10

Kendall Helmstetter Gelner