In my program I have a class, say ClassA. I'd like to create a derived class, say ClassB. My program has functions returning instances of ClassA and in certain cases I'd like to use these returns to create an instance of ClassB. Doing the naive downcasting doesn't lead to any compiler errors, but runtime errors creep in. This seems to be related to issues about casting pointers vs. objects -- at any rate, from what I've read, this was the wrong thing to do in this case.
I then attempted to mimic the copy-constructors of C++, but variables that were copied passed out of scope or were released, leading again to run-time errors.
I also considered using categories but this doesn't seem right for two reasons:
I'm still learning Objective-C. I know there are some similar questions in the forum but the answers either led to categories and dead-ended or dead-ended without much help so I felt I should simply repost.
In my program I have a class, say ClassA. I'd like to create a derived class, say ClassB.
@class MONClassA;
@interface MONClassB : MONClassA
{
int anotherVariable;
}
//...
- (id)initWithMONClassA:(MONClassA *)classA anotherVariable:(int)anotherVar;
@end
My program has functions returning instances of ClassA and in certain cases I'd like to use these returns to create an instance of ClassB.
same way you'd do it in c++ (as it sounds like that's your background), promote the type with a new instance:
//...
MONClassA * a = SomeLibFunction();
MONClassB * b = [[MONClassB alloc] initWithMONClassA:a anotherVariable:???];
//...
Doing the naive downcasting doesn't lead to any compiler errors, but runtime errors creep in. This seems to be related to issues about casting pointers vs. objects -- at any rate, from what I've read, this was the wrong thing to do in this case.
correct - it is the wrong thing to do.
I then attempted to mimic the copy-constructors of C++, but variables that were copied passed out of scope or were released, leading again to run-time errors.
see the above implementation to see how to promote a type in objc. this of course assumes you'll also define an appropriate implementation for initialization (equivalent to your cpp constructor and copy constructor).
I also considered using categories but this doesn't seem right...
then your instinct is probably right. this language feature is misused quite often.
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