简体   繁体   中英

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

For example:

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

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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM