Let's say a have a Superclass
and an instance of this class superclassObject
.
I create a derived ClassA
.
How can I instantiate (initialize) an object classAObject
of the derived class in a such way, that all the inherited fields are equal to ones of superclassObject
?
Of course I can cycle through all the fields and manually copy the values like classAObject.property = [superclassObject.property copy]
. But the problem with this approach is that I may not know (or have access to) all the ivars/properties of the superclass.
Is there an easier (and more general) way?
It seems that I'm missing something really basic...
I'm trying to do this because I get an already initialized UIView (with frame, background color, autoresizing mask, etc.) and I want to replace it with my custom view with same parameters.
I've found this question, and the answer there says that it
generally isn't supported in any OO language
however
In Objective-C it is possible in some cases
Ok, if it's not supported, what should I do? If it is supported, how can I achieve this?
It seems I've found a solution to my particular case of this general problem, which I'll test and report that tomorrow.
However, this lead me to another idea: What if I use a NSCoder to encode the superclassObject
(if it implements <NSCoding>
of course), and then call [[ClassA alloc] initWithCoder:coder]
with a coder that knows data from the encoded superclassObject
? Disclaimer: Well, I'm not that familiar with coding concepts (or even not at all), so may be the last sentence is nonsense.
No. It makes zero sense to allow that. The reason is because subclasses generally define additional behavior. If you could assign a superclass object to a subclass reference, you would run into problems at runtime when you try to access class members that don't actually exist.
Yes, the super class reference variable can hold the sub class object actually, it is widening in case of objects (Conversion of lower datatype to a higher datatype).
Subclass methods can call superclass methods if both methods have the same name. From the subclass, reference the method name and superclass name with the @ symbol.
If I understand the question correctly, you have an established view which you want to change to a different class. Presumably for the reason of changing it's functionality.
Cloning class properties between classes and swapping instances is the only way to do this sort of thing in languages like Java.
But ... in Objective C we have Categories. If all you are trying to do is change behaviour then perhaps a solution might be to create a Category for UIView that performs the additional or overridden functionality you require.
Second thought is to look into why you are not creating the correct class in the first place and therefore avoid this whole problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With