I am curious how to instead of doing:
- (id)init {
if ((self = [super init])) {
//initialize subclass objects
}
return self;
}
Initialize the subclass by passing a perimeter of the superclass object
- (id)initWithSuperclass:(Superclass *)superclassObject {
if ((self = superclass)) {
//initialize subclass objects
}
return self;
}
Is this possible and if so, is it something that I should avoid? To me, it reeks of smelly code but I don't see another way of passing all the data fields of a superclass object to an initialization of a subclass without knowing every data field in the superclass.
Anyone following my thought/able to help me figure a way through this... smelly code?
Edit:
Ok, so say I have class A and class B below:
#interface A
//stuff but we don't know what
end
#implementation A
- (id)init {
if (self = [super init]) {
//initialize A "stuff"
}
return self;
}
end
#interface B : A
#property (nonatomic, retain) UIButton* one;
- initWithA:(A*)superclassObject;
end
#implementation B
- (id)initWithA:(A*)superclassObject {
if ((self = superclassObject)) {
one = [[UIButton alloc] init];
}
return self;
}
end
The advantage to doing this that I am looking for is that in class A, I do not know all the data fields because it is not my code/code I have access to. I do however need to extend that class. I want to be able to change instances of class A into class B by introducing new data values for class B (like "UIButton one" in the above example) on top of whatever data values/objects may be part of the object instance of class A.
Ignoring obscure advanced features of the runtime, what you are trying to do is not possible in Objective-C - you cannot dynamically extend an object instance from a superclass to a subclass instance adding instance variables in the process.
Think instead of the "has a" model - where B is not a subclass of A but has an instance variable/property of type A.
HTH
Addendum
Seeing your new comments regarding MYButton vs UIButton, why create UIButton instances at all? If you are using Interface Builder/Xcode to generate your UI then you can construct your MYButtons directly - select a UIButton in the designer and change its class to MYButton, see the docs for how, and then you'll create your instances directly.
Related
This is something very fascinating I observed today. Maybe that's how Objective-C works but I didn't know about this. See the following code below:
// ATableViewController.h
#interface ATableViewController : UITableViewController
#end
// ATableViewController.m
#interface ATableViewController ()
#property (nonatomic) int volly;
#end
#implementation ATableViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.volly = 5;
}
#end
// BTableViewController.h
#interface BTableViewController : ATableViewController
#end
// BTableViewController.m
#interface BTableViewController ()
#property (nonatomic) int volly;
#end
#implementation BTableViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"%d", self.volly); // returns 5
}
#end
I am not sure why the above is valid. I do understand that I passed a message 'volly' to the object 'self' which in turn probably looked at the value from the super class but shouldn't these be initialized? Some explanation would be of great help. Thanks.
EDIT: This is a big problem IMO though. Considering I don't know any of the private properties defined in the super class, my own set of values might end up being different.
For example, a developer may set a boolean flag hasAppeared in viewDidAppear:. This same value will be set for my subclass instance in viewDidAppear: after the [super viewDidAppear:] call. This will be before I actually get to set it myself.
Currently, the solution is I know exactly the variable used by the super class and I can avoid using the same value but I deem this to be a larger issue than it seems.
EDIT 2: The behavior is consistent with binaries (with only headers) as well as with frameworks where implementation is available.
I am answering this without reading all of the comments.
There is no issue here. Both AViewController (AVC) and BViewController (BVC) each have their own private property named volly.
You created an instance of BVC. It can't see the volly property from its parent class (because it is private), just its own.
Now the fun begins.
The viewDidLoad method from BVC is called. It in turn calls [super viewDidLoad]; which of course calls the viewDidLoad from the AVC class. That method, in turn, calls self.volly = 5;.
The confusion seems to be with this line. Remember, self.volly = 5; is really a call to:
[self setVolly:5];
Both AVC and BVC have the (synthesized) setVolly: method. Since self is a pointer to an instance of a BVC object, the call to [self setVolly:5]; results in a call to the setVolly: method in the BVC class despite being called from a method in the AVC class.
Here's the code with some annotations:
The 'BVC' class:
- (void)viewDidLoad
{
[super viewDidLoad]; // calls the method in `AVC`
NSLog(#"%d", self.volly); // returns 5
}
The 'AVC' class:
- (void)viewDidLoad
{
[super viewDidLoad]; // calls the UITableViewController method
// The following is really [self setVolly:5];
// Since "self" is a "BVC", the private "volly" property of
// the "BVC" class is actually set here.
// The private "volly" property of the "AVC" class will still be
// 0 after this call.
self.volly = 5;
}
In the end, the subclass is not using the private property of the parent class. The original premise in the question's title is incorrect.
I have a superclass and subclasses in the following format:
ParentClass.h
#interface ParentClass : NSObject
-(ParentClass *)field:(NSArray *)fields;
#end
ParentClass.m
#import "ParentClass.h"
#implementation ParentClass
-(id)init{
self = [super init];
if (self == nil) {
return self;
}
return self;
}
-(ParentClass *)field:(NSArray *)fields{
ParentClass *pc = [[ParentClass alloc] init];
// code
return pc;
}
#end
Subclass.h
#interface Subclass : ParentClass
-(Subclass *)field:(NSArray *)fields;
#end
Subclass.m
#import "Subclass.h"
#implementation Subclass
-(id)init{
self = [super init];
if (self == nil) {
return self;
}
return self;
}
-(Subclass *)field:(NSArray *)fields{
// code
return (Subclass *)[self field:fields];
}
#end
I guess the issue is here.
return (Subclass *)[self field:fields];
I'm not accessing the parent class method the way I should. Can anyone tell what should be the right way instead?
What if i call this way?
-(Subclass *)subClassField:(NSArray *)fields{
return (Subclass *)[self field:fields];
}
and i replaced the
-(Subclass *)field:(NSArray *)fields;
with
-(Subclass *)subClassField:(NSArray *)fields;
First please note that this code
-(ParentClass *)field:(NSArray *)fields{
ParentClass *pc = [[ParentClass alloc] init];
// code
return pc;
}
Doesn't look right from the software design perspective. From what you posted it seems that ParentClass instances can create and return other instances of its own type from the field method. This doesn't look ok, but it could be fine depending on what your intentions are.
Consider making ParentClass and FieldClass different classes if that makes sense.
Regarding the subclass, the way of doing what you want would be this:
-(ParentClass *)field:(NSArray *)fields
{
// code
return [super field:fields];
}
Note that I changed the returned type to be (ParentClass *), and the self to super. You cannot return a ParentClass object in the place of a SubClass object (the latter could have extra data that former doesn't know about). Doing the opposite is valid (you can return a Subclass object when someone expects to receive an object of ParentClass type).
Having said that is pretty unclear what you're trying to achieve, I'll tell what's wrong. First of all isn't enough to cast a pointer to a base class pointer, to call the superclass method, you should call it this way:
return (Subclass*) [super field:fields]; // Still wrong
But you're break polymorphism, and as the method signature says, you're returning a Subclass object, and the user that calls this method expects to have a Subclass object, but at the first call of a method that is just implemented by the subclass, it crashes because you're returning an instance of the superclass. Maybe is enough for you to change the method signature to return a ParentClass pointer, but this makes the method useless, why overriding it? It isn't pretty clear what you're trying to do, and what's your logic path.
Edit
Having seen the code that you posted on Github, here the situation is pretty different. In the Java code,t he method field returns this, so no new object gets created, and the method is just used for side effects. The add method doesn't break polymorphism, because just the object reference is of the parent class type, but if executed on a subclass it returns the object itself (this), which is of the subclass type.
In Objective-C for these cases the id type is used, which is used to represent a whatever object pointer, to a whatever class. You could also use the ParentClass type, but I'll stick to conventions. Here's an indicative code:
#implementation ParentClass
#synthesize endpoint
- (id) add: (NSString*) endpoint fields: (NSArray*) fields
{
<code>
return self;
}
- (id) field: (NSArray*) fields
{
return [self add: self.endpoint fields: fields];
}
#end
#implementation SubClass
- (id) field: (NSArray*) fields
{
< Additional code >
return [self add: self.endpoint fields: fields];
}
#end
Basically I have a class hierarchy something like this:
NSObject
MySpecialController
MyExtraSpecialController
Each of these has an init method, and each implementation calls super first to let the superclass initialize itself first, all the way up the chain. For lack of better terminology I would say that each class "augments" its super class' behaviour.
But let's suppose I want to "replace" my super class's behaviour entirely (simply because I want to specialize it further for a particular app, but without cluttering the generic reusable super class. So it is assumed that I have intimate knowledge of the super class). The actual change that I want to do is replace a property with one of a more specific class type. To fully implement this I need the init method to instantiate an instance of widget of the appropriate class. So if I instantiate a MySpecialController, its widget property should be of type MySpecialWidget; but if I instantiate a MyExtraSpecialController, its widget should be of type MyExtraSpecialWidget:
//MySpecialController:
#interface MySpecialController : NSObject
#property (strong, nonatomic) MySpecialWidget *widget;
#end
#implementation MySpecialController
-(id)init {
if (self = [super init]) {
self.widget = [MySpecialWidget new];
}
}
#end
//MyExtraSpecialController:
#interface MyExtraSpecialController : MySpecialController
#property (strong, nonatomic) MyExtraSpecialWidget *widget;
#end
#implementation MyExtraSpecialController
-(id)init {
if (self = [super init]) {
self.widget = [MyExtraSpecialWidget new];
}
}
#end
Now this works in the sense that MySpecialController works, and can be used by anyone with the public API. And MyExtraSpecialController also works, and follows proper separation of concerns as it assumed nothing about the superclass's behaviour. This is the type of subclass one would create of a framework or library class: robust and unassuming.
What actually happens though is that when I create a new instance of MyExtraSpecialController, its superclass first instantiates a MySpecialWidget, and then it immediately deallocates that instance and replaces it with an instance of MyExtraSpecialWidget. Sure this works, but since I DO have intimate knowledge of the superclass (which basically means that I know exactly what its init method does, so I can safely replace it without needing to call it first), I want to avoid this problem and only instantiate a single widget (it just so happens that creating a widget is really expensive and isn't premature optimization). So I want to replace super's implementation entirely so that it doesn't create a widget, and will replace everything else that it does based on my intimate knowledge, but, and this is key, I still want to call init further up the chain because I don't know what my replaced class' superclass' init method does (NSObject in this case), as this is a class I don't have intimate knowledge of.
The immediate solution that comes to mind is to use the Objective-C dynamic runtime to get hold of the grandparent instance, and just call its init (which will then take care of calling up the chain if it needs to), therewith bypassing super. But whenever I find myself about to do something like that I always wonder if there is a better approach altogether--conceptually speaking, i.e. to replace rather than augment a superclass' method. Is there?
You could remove the instantiation of self.widget from the init functions and implement a custom "lazy" getter function instead:
- (MySpecialWidget *)widget
{
if (_widget == nil) {
_wigdet = [MySpecialWidget new];
}
return _widget;
}
Then you can override this method in the subclass. The widget will be created on the first access to self.widget, and either the superclass or the subclass getter is called.
One easy way to solve this would be to create a hook for making the widget.
#implementation MySpecialController
-(id)init {
if (self = [super init]) {
self.widget = [self makeWidget];
}
}
- (MySpecialWidget*) makeWidget
{
[MySpecialWidget new];
#end
Then your subclass can override makeWidget to return a VerySpecialWidget. This makes sense when you don't want clients to know about these widgets.
In your scenario, it's possible that clients know something about the widgets -- e.g. they want a VerySpecialController in order to get a VerySpecialWidget. If that's the case, you might want to let the client pick the widget:
[MySpecialController initWith: [MyVerySpecialWidget new]];
If the widget is the primary force for making the subclass, either approach may eliminate the need to sprout the subclass in the first place.
The second approach has the additional advantage of making unit testing easier; you can build a MySpecialController and pass it a dummy, stub, or mock without any fuss:
[MySpecialController initWith: [MyTestObjectThatPretendsToBeAWidget new]];
But the first pattern is cleaner if the clients shouldn't know anything about widgets.
One approach is to add an instance method -widgetClass to MySpecialController
#implementation MySpecialController
- (id)init
{
self = [super init];
if (self) {
self.widget = [[[self widgetClass] alloc] init];
}
return self;
}
- (id)widgetClass
{
return [MySpecialWidget class];
}
//...
#end
and override that method in MyExtraSpecialController
#implementation MyExtraSpecialController
- (id)widgetClass
{
return [MyExtraSpecialWidget class];
}
//...
#end
Assume there is an object that initialises like so
- (void)doInit
{
NSLog(#"In BaseClass init");
}
- (id)init
{
self = [super init];
[self doInit];
return self;
}
and it has a subclass which is inited in a similar way
- (void)doInit
{
NSLog (#"In SubClass init");
}
- (id)init
{
self = [super init];
[self doInit];
return self;
}
Now if I create an instance of child class then I receive the following output:
In SubClass init
In SubClass init
when really, what I meant to happen is
In BaseClass init
In SubClass init
Is there a way to mark doInit to say that it shouldn't be overridden or do I need to create a unique name for all methods in a subclass?
I'm not entirely sure how I haven't come across this issue before, but there you go.
Edit:
I understand why this is happening, I hadn't expected that the base class would be able to call the overridden function.
I also can't just call [super doInit]; from the Subclass method because the BaseClass still needs to call doInit so that creating an instance of BaseClass will still work. If I called [super doInit], I'd still end up getting SubClass's doInit called twice.
It appears the answer is no and I'll just have to uniquely name each doInit like doBaseClassInit and doSubClassInit.
If you have a method that you don't want to by dynamically bound (i.e. don't want a subclass method to be called if it exists), you need to do it as a C function instead. So, you could do this instead:
In the base class:
static void DoInit(BaseClass *self)
{
NSLog(#"In BaseClass init");
}
- (id)init
{
self = [super init];
if (self) {
DoInit(self);
}
return self;
}
in the subclass:
static void DoInit(SubClass *self)
{
NSLog(#"In SubClass init");
}
- (id)init
{
self = [super init];
if (self) {
DoInit(self);
}
return self;
}
Note that both the DoInit methods are marked as static, so they are only visible each compilation unit (.m file) and don't conflict with each other.
You could, perhaps, try something like this in your base class. It would mean any time the init implementation inside BaseClass executed, the doInit implementation for BaseClass would be called.
- (void)doInit
{
NSLog(#"In BaseClass init");
}
- (id)init
{
self = [super init];
Class baseClass = [BaseClass class];
SEL selector = #selector(doInit);
IMP baseClassImplementation = class_getInstanceMethod(baseClass, selector);
baseClassImplementation(self, selector);
return self;
}
As I mentioned in my comment, if that's the narrowness of your need this should work as it gets around the dynamic method lookup involved with sending a message. Hope this helps!
EDIT:
Disclaimer - if you're in this situation it's probably not a good sign for the longevity of your design. This technique will get you up and running for now but please document it carefully, and consider ways to refactor your code so this is no longer used. Consider fixes like these to really be used only when extremely urgent.
The reason why you are not getting the "In BaseClass init" console message is because your subclass is not calling the super's implementation of doInit.
If you don't want doInit overridden the 'best' way to avoid doing so is to not publish the existence of this method. Remove it from your header and uniquely name the method so that a collision is unlikely. For example, many of the private methods in Apple's frameworks have a leading underscore. So, for example, you could call your method _doInit and it will be very unlikely that a subclass accidentally create it's own overiding implementation.
Nope, there's no enforceable way to prevent a subclass from overriding a method. The best you can do is to avoid putting it in the public header file for the class so someone is not likely to try to override it. If the method has to be public, you just put a note in the documentation for the method that it shouldn't be overridden or that subclasses should call super's implementation whichever the case may be. You'll find these kind of instructions all over in the documentation for Apple's own classes.
If you want your subclass to use the baseclass version of doInit then in the subclass don't declare a doInit method. Here's what I mean:
ClassA:
#interface ClassA :
-(void) doInit;
-(id) init;
#implementation
-(void) doInit {
NSLog(#"ClassA doInit");
}
-(id) init {
self = [super init];
if (self != NULL)
[self doInit];
return self;
}
ClassB
#interface ClassB : ClassA
-(id) init;
#implementation
-(id) init {
self = [super init];
if (self != NULL)
[self doInit];
return self;
}
And really you don't need to override the init method as well unless there's some special code that you want that class to do.
I have two Objective-C classes and one is derived from the other as
#interface DerivedClass : BaseClass
{
}
The code section below belongs to BaseClass:
- (id)init {
if (self = [super init]) {
[self configure];
}
return self;
}
- (void) configure{} //this is an empty method
And the code section belongs to the DerivedClass:
-(void) configure{
NSLog(#"derived configure called");
}
Now, when I say derivedInstance = [DerivedClass new]; and watch the call stack, I see that the configure method of my derived class gets called at the [self configure] line of the base's init method.
I'm an Objective-C noob and I'm confused about how a method of a derived class gets called from the method of a base class. "self" keyword is explained to be the same thing as "this" keyword of some languages but I think this explanation is not completely correct, right?
[self someMessage] will send the message "someMessage" to the current object, which is an instance of DerivedClass.
Message dispatch is done dynamically at run-time, so it will behave as whatever the object is at that time.