qrikko
qrikko

Reputation: 2603

Categories best practices

I am wrapping my head around using categories for some things where I might previously have been using inheritance.

The thing I am doing now is more of a best-practice question where I am not sure how it should be implemented. I am writing a category on UIActivityIndicatorView which basically will be used to put a activity indicator in an arbitrary view. Below you'll find the code example of how I am doing it and my main question is whether or not this is good. And I would appreciate comments on why it's bad if that is the case. Thanks.

The category:

@interface UIActivityIndicatorView (Customizations)
    - (UIActivityIndicatorView *) inView:(UIView *) target;
@end

Implementation:

@implementation UIActivityIndicatorView (Customizations)

- (UIActivityIndicatorView *) inView:(UIView *) target {
    [self startAnimating];
    [self setHidden:NO];
    self.frame = target.bounds;
    self.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.6f];

    return self;
}
@end

Then I would use it like this:

[background addSubview:[loader inView:background]];

I am guessing that another way of doing it would be to make an initialization function to take the container view and just return the "styled" view, or perhaps not return anything (void) and just let the method do the styling.

So I am looking for some guidance as to how to handle this.

Upvotes: 2

Views: 592

Answers (1)

geon
geon

Reputation: 8479

What kind of worries me is that I am actually making a second copy of the UIActivityIndicatorView which seem unnecessary

No, you don't. You might be confused by the fact that you are returning self from your category method, but that is just a pointer, not the object itself getting copied.

However, I would implement it slightly different:

- (void) addToSuperView:(UIView *) target {
    [self startAnimating];
    [self setHidden:NO];
    self.frame = target.bounds;
    self.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.6f];

    [target addSubview:self];
}

That way, you don't need to make an extra, unnecessary call when adding it:

[loader addToSuperView:background];

Upvotes: 4

Related Questions