Can anybody tell me when to use categories and when to use subclassing in Objective-C? Also please tell me the advantages and disadvantages of them.
An objective-c category is useful if you want to alter the behavior of ALL instances of the class, with minimal code. Subclassing is more useful if you want to alter the behavior of only certain instances, and retain the original method for others.
Categories can be dangerous, especially if you cannot view the source of the original method, so you should generally use subclasses on third-party and private frameworks rather than a category.
Category : It is used if we want to add any method on a given class whose source is not known. This is basically used when we want to alter the behaviour of any Class.
For example : If we want to add a method on NSString to reverse a string we can go for categories.
Subclassing : If we want to modify state as well as behaviour of any class or override any methods to alter the behaviour of the parent class then we go for subclassing.
For example : We subclass UIView to alter its state and behaviour in our iOS code.
Adding to what coneybeare said. Subclassing is a better option for customization, and Categories are better to be used when you just want to add some functionality to existing classes.
Do you want to change something which happens as part of framework calls during the lifecycle of a UI object? Use Subclass. Override respective methods, such as init, drawrect, layoutsubviews etc.
Do you want something application wide, something which is in
addition to the existing functionality, and you don't care if this
becomes available to all instances of this pre-existing instances of the framework class? Use categories. Example: animate UILabel upon certain user action, and apply this animation through out your app to all UILabel instances.
© 2022 - 2024 — McMap. All rights reserved.