override classes variable, or at least variable ty

2019-06-05 14:21发布

问题:

My dilemma is as follows:

I have a custom subclass of UIImage (I've added some serialization methods i.e. initWithCoder, encodeWithCoder), and I would like to apply my custom subclass as a variable to a UIImageView, or at least a subclass of UIImageView.

As you are aware, UIImageView has a variable called "image", that is of type UIImage. I'd like to override this variable with my subclass.

My goal is to have a UIimageView that will respond to archivedDataWithRootObject without crashing with the encodeWithCoder message is sent to the variable image. If there is a smarter way to get there, I'm open to suggestions.

Thank you!

[edit] I think one possible route is through some type of casting...However:

UIImage *image = [[UIImage alloc] init];
MLImage *mlImage = [[MLImage alloc] init];
mlIamge = (MLImage*)image;

When I mouse-over mlImage after the second line executes, I can see that it is of type MLImage. However, even with the cast, after the third line executes mlImage becomes a UIImage. What do I need to do to change the type of image to MLImage? [/edit]

回答1:

Be careful with your terminology. It's not possible to override a property—the UIImageView will still have its own image property, it won't be replaced. You're trying to override the accessors (-image and -setImage:).

And you're right, casting is a better route. But your example has a problem: that cast is illegal. When you do [[UIImage alloc] init], you're creating an object of type UIImage. Nothing is going to change that, including your cast. Casting is a way of telling the compiler (in your case) "I know you think that this UIImage* is, well, a UIImage, but it's really a MLImage." In this case, that's a lie, since it really is a UIImage—you allocated it right there.

What you can do, though, is stick an actual MLImage into the image property of a UIImageView. For example:

MLImage *myImage = [[MLImage alloc] init];
myView.image = myImage;

And then somewhere else:

MLImage *myImage = (MLImage *)(myView.image);

And you'll get back your custom image object. But it has to have been an MLImage in the first place.