Say I have this Class
@interface CustomClass : NSObject
@property (nonatomic, strong) NSArray * nicestArrayEver;
@end
And I want to create a subClass of CustomClass, but here is the catch
@interface ASubClassCustomClass : CustomClass
@property (nonatomic, strong) NSMutableArray * nicestArrayEver;
@end
The issue as you can imagine is that when I initialize ASubClassCustomClass and call it’s super initializer (since there is other properties required) the inmutable nicestArrayEver is created.. how can I avoid it’s creation so I can set the mutable one?
Note: This is just an example, the real implementation calls a heavy to create and really customized subclass (is not an NSArray).
You can make it work, by using different backing variables, when synthesizing it looks like this:
@synthesize nicestArrayEver = nicestArrayEverSubClass_;output
Another approach could be to have 2 init methods in the base class, one, that will instantiate the property and one, that won’t, but leaves that task for the child class — this will prevent you from creating expensive objects just to throw them away.
Now the base class could get instantiated directly with the second init and go to a false state. You can avoid this by checking the self class type with
isMemberOfClass:, and throw an error, if the class type is the base class.