Marco
Marco

Reputation: 803

Initialize a subclass from a superclass in Objective C

I have created a UIImage subclass named MyImage. MyImage obviously responds to every method originally implemented by UIImage. I would like to completely hide UIImage implementation, so for example MyImage redeclares a method like:

- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets;

to

- (MyImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets; 

I attempt to write the implementation like:

- (MyImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets {
    UIImage *original = [super resizableImageWithCapInsets:capInsets];
    MyImage *result = [[[self class] alloc] initWithUIImage:original];
    return result;
}

- (id) initWithUIImage:(UIImage *)image {
    // HOW TO IMPLEMENT THIS METHOD???
}

but I stopped at initWithUIImage method. How can I achieve such a behavior without using composition?

Upvotes: 0

Views: 373

Answers (3)

Dancreek
Dancreek

Reputation: 9544

You don't want to do that. Its a lot of unnecessary code with a high risk of breaking something. Don't redeclare these methods. Is there a specific reason that you want to do that?

Upvotes: 1

Ben Baron
Ben Baron

Reputation: 14815

The answer is that you cannot do what it seems like you're attempting to do. MyImage IS a UIImage, meaning it implicitly has all methods and properties of UIImage. You can add new ones, but never remove existing ones.

And UIImage is used all over the system APIs. What exactly are you attempting to accomplish by doing this?

Upvotes: 0

Marek R
Marek R

Reputation: 38112

The problem here is simple and it is called: INHARITANCE.

Do not do inaritance but provide some class which owns UIImage. It will be easier and more relialeble.

Another issue is that you didn't expain why you need change something in UIImage! I'm prety sure yuo are trying to resolve some simple problem in nasty way.

Upvotes: 0

Related Questions