objective-cclassoopobjective-c-category

Extend Class or Create a Category to Customize Existing Frameworks?


I need to customize some methods and properties of existing classes from some third-party framework. I know that I can extend the class or create a Category. But which approach works better if I want to keep the source of framework untouched and only create my own additions/extensions?

In my particular case, I want to retrieve a private property of class SomeClass:NSObject declared in .m file as:

SomeClass.m

@interface SomeClass() 
@property (nonatomic, strong) NSString *string;
//...
@end

@implementation SomeClass 
//....
@end 

Solution

  • Use a category. A category will work for all subclasses of the class, and not merely for your one subclass. For example, say that you want to be able to get a UIImage of an arbitrary UIView. If you subclass UIView, and then want to use the method on a UIScrollView, you won't be able to use the method without making another subclass for UIScrollView, and every other class in the hierarchy you want to use the method on.

    Another reason not to use a subclass is that if you have a method in your framework which returns an instance of a class such as

    +(classWithAPrivateProperty*) getClassWithPrivateProperty

    you'll have to make a new member of your subclass with the data from that class before you can access the property.