SimplyKiwi
SimplyKiwi

Reputation: 12444

Call method in another class by Casting?

Ok so lets say I have Class A and Class B. In Class A lets say I implemented a method called saveImage and implemented the method in the .m.

Is it simple enough to say that if I do [(ClassA*)self saveImage]; That method in Class A will get called?

What is the logic behind this and can anyone explain it so I can understand a bit better?

Thanks!

Upvotes: 1

Views: 235

Answers (1)

Jack Lawrence
Jack Lawrence

Reputation: 10772

Casting is mostly just for compile-time type checking (note that for safety, it's always wise to cast when you send a message to an object of type id. See here. It's ignored by the compiler (and therefore the runtime). Casting is just a promise to the compiler that yes, that object is really is really Class A, not Class B. So if you tried to compile that, unless self is actually an instance of Class A or a subclass (as you promised), you're going to raise an exception. AKA the runtime will get mad if you break your promises :)

Upvotes: 2

Related Questions