1

See the code:

@implementation UIView (ios7)
- (void)layoutSubviews
{
    [self layoutSubviews];
    // ......
}

Obviously ,this will result in “Infinite recursion”. Super is not helpful either. I just want to add some code to a common fucntion in a common class,and do not think Inherit will help. So,is their any way to do this.Or my requirement is just stupid. Thanks!

++++++++++++++++++++++++++

@interface CPUIView :UIView
- (void)layoutSubviews;
@end
...


@implementation CPUIView
- (void)layoutSubviews
{
    [super layoutSubviews];
    // add some code
}
@end


@implementation UIView (CP)

+ (Class)class
{
    return NSClassFromString(@"CPUIView");
}

I think this code will help me with my problem,I just want to rewrite the layoutSubviews function for the UIView .Thus, any UIView class in my project will do what I want then to do in this function.

shadox
  • 997
  • 1
  • 8
  • 18
  • 1
    Short answer: there is no way to call the original method and you should not override existing methods from categories. – BergQuester Dec 17 '13 at 03:32
  • it is [possible](http://www.cocoawithlove.com/2008/03/supersequent-implementation.html) but don't do it. – Bryan Chen Dec 17 '13 at 04:40

2 Answers2

0

Categories are meant to add methods to a class, not replace them. That's what subclasses are for. You're much better off creating a subclass instead, which you can then call...

[super layoutSubviews];

... if you need to call the original UIView method.

For example:

@interface ESExampleView : UIView

@end

@implementation ESExampleView

- (void)layoutSubviews{
    NSLog(@"layoutSubviews called!"); //Do whatever
    [super layoutSubviews];
}

@end
eswick
  • 519
  • 4
  • 16
0

Like @eswick said, categories are for adding methods to objects. By declaring a method with the same name as an existing method, you are effectively overwriting the old method. Therefore, you cannot call it because you've replaced it. This is why you'll need to subclass if you want to retain the functionality of that method.

gdavis
  • 2,556
  • 1
  • 20
  • 25