What is the point of declaring a variable as one class, and allocating memory to it with another class?

51 views Asked by At

For example:

UIImageView * imageView = [[MyCustomImageView alloc] init];

What is the benefit of doing this? Why not do?:

MyCustomImageView * imageView = [[MyCustomImageView alloc] init];
2

There are 2 answers

2
Christian Schnorr On BEST ANSWER

The benefit is that you can hide implementation details to yourself and to the outside.

If you are going to return this value from a method for example, the outside may not care about what kind of image view it is - as long as it is some kind of it! If it's a private class you are creating, you may not even want to expose that this class exists to the outside.

In other languages with proper interfaces, this is a more well known pattern. This article is a good read.

0
Dan Loughney On

There are important uses for both. In both cases, I'm assuming that MyCustomImageView inherits from UIImageView...

UIImageView * imageView = [[MyCustomImageView alloc] init];

Assigning a different object to its parent's type is used to extend the standard functionality of UIImageView by overriding public methods and properties and only those. You could, for example, deliver an entirely different image presentation by implementing MyCustomImageView layoutSubviews or drawRect with no other logic in your view controller.

MyCustomImageView * imageView = [[MyCustomImageView alloc] init];

With a declared pointer to MyCustomImageView you can override the public methods and declare new properties and methods that your app requires like invertImage, blinkImage, etc.