Niko
Niko

Reputation: 3422

Prevent custom class from being altered by a category

Let's assume we have a custom lib with a class that inherits from UILabel:

//MyLibCustomLabel.h
@interface MyLibCustomLabel : UILabel

MyLibCustomLabel is linked to a UILabel in a .xib file, and text is filled in .xib.

This custom lib is integrated in a project that has a Category on UILabel class, which has a method to modify UIlabel's text

//UILabel+UILabelAdditions.h
@interface UILabel (UILabelAdditions)


//UILabel+UILabelAdditions.m
@implementation UILabel (UILabelAdditions)

- (void)awakeFromNib {
    [super awakeFromNib];

    [self prependText];
}

-(void)prependText {
    NSString *newText = [NSString stringWithFormat:@"blabla + %@", self.text];
    self.text = newText;
}

In the end, there is a modification non-desired in MyLibCustomLabel.

In a situation of both custom class and category are used in a Class, is there a way to protect MyLibCustomLabel from any Category on UILabel ?

So that MyLibCustomLabel can not be altered in an undesired way, and so that there is no modification to do in the project that integrates it.

Thanks for your help !

Upvotes: 0

Views: 35

Answers (1)

rmaddy
rmaddy

Reputation: 318824

There is nothing that can be done to "protect" a class from a possible category being defined.

But please note that the example UILabel category you show isn't valid. A category must never attempt to override an existing method nor attempt to call a super method. Such behavior isn't defined and isn't guaranteed to work as hoped.

In other words, the category's awakeFromNib method is a bad idea and shouldn't be done. Such a thing should only be attempted in a base class, not a category.

Upvotes: 1

Related Questions