tags:

views:

39

answers:

2

Hi everyone!

I need to convert a custom object to a different object. How can I do that?

I know that typecasting doesn't work (the only thing is does is "shuts the compiler warnings off", but nothing more). Here is a sample code:

MyType* obj1;
MyOtherType* obj2;

obj1 = [MyType initWithData: 1];
obj2 = (MyOtherType*) obj1;

if ([obj2 isMemberOfClass: [MyOtherType class]]) { NSLog(@"OK"); }
else if ([obj2 isMemberOfClass: [MyType class]]) { NSLog(@"Nope"); }

The result is:

Nope

What can I do??

A: 

You can do it manually, field-by-field. Or create a method in MyType that does it manually and returns MyOtherType.

Alexander Babaev
The thing is that MyOtherType extends MyType (I have showed a simplified version of my code here for convenience). So isn't there a better way?
Nastase Ion
You can never "convert" any object to any object automatically. Only by hand. Typecasting only gives you an ability to look at an object through "colored glasses". But the object still is the same.
Alexander Babaev
+2  A: 

Typecasting (like you're doing) isn't going to change the type of the object. What you're actually doing is this:

obj1 = [MyType initWithData: 1];

"I just created a object of type MyType, now point obj1 at it. Since obj1 is a MyType pointer, it's okay."

If you were to the next line without the typecast:

obj2 = obj1;

You're saying, "point obj2 at the same thing obj1 is pointing to", which will work but the compiler know obj1 is a MyType pointer and obj2 is a MyOtherType pointer so it throws a warning telling you they are incompatible.

So when you say:

obj2 = (MyOtherType*) obj1;

All you're saying is, "point obj2 at the same thing obj1 is pointing to, OH and treat obj1 as if it were an MyOtherType object". This is cool with the compiler since as far as it is concerned it's just assigning a MyOtherType to a MyOtherType. But this doesn't actually change the object that obj1 is pointing to. So when you pass the 'isMemberOfClass' message to obj1, it's still going to be and report that it is a member of MyType.

One solution to your problem would be to write your own custom initializer or converter (something like this):

- (id)initWithMyType:(MyType*)originalType;

And then do the conversion in there

ACBurk
Nice answer. I always think of typecasting as "interpret the chunk of bytes at this address in that manner".
Frank Shearar