Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get subclass to initialize property as its correct class?

I have a class named SPPanelManager, which has a property of another class, named SPPanelSettingsManager. SPPanelManager has the following in it's -init method:

self.settingsManager = [[SPPanelSettingsManager alloc] init];

The purpose of SPPanelManager is to be subclassed, and the subclasses are used throughout my app. For example, there's SPGreetingManager. In the .h file of SPGreetingManager, I have declared:

@property (nonatomic, strong) SPGreetingSettingsManager *settingsManager;

which makes the settingsManager be of the correct class. The problem is that when the SPGreetingManager subclass is initialized, it calls the init method above, and initializes the settingsManager as the SPPanelSettingsManager class, rather than SPGreetingSettingsManager.

How can I get it to initialize this as the correct class for that property without having to re-write the init code in every subclass?

like image 650
Andrew Avatar asked Jan 12 '23 15:01

Andrew


1 Answers

The super class (SPPanelManager) somehow has to know which class the concrete panel manager wants to use as a settingsManager.

Apple uses the following approach to match CALayers to UIViews:

The base class declares a class method that returns the concrete SPPanelSettingsManager subclass:

// in SPPanelManager.h
+ (Class)settingsManagerClass;

... which subclasses override to return their custom class:

// in SPGreetingManager.m
+ (Class)settingsManagerClass
{
    return [SPGreetingSettingsManager class];
}

Now the superclass can instantiate the settings manager as follows:

self.settingsManager = [[[[self class] settingsManagerClass] alloc] init];
like image 150
Nikolai Ruhe Avatar answered Jan 25 '23 18:01

Nikolai Ruhe