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.
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- back button text does not change
- iOS (objective-c) compression_decode_buffer() retu
- Diffrence between assigning simple prototype and u
相关文章
- 现在使用swift开发ios应用好还是swift?
- TCC __TCCAccessRequest_block_invoke
- xcode 4 garbage collection removed?
- Unable to process app at this time due to a genera
- How can I add media attachments to my push notific
- didBeginContact:(SKPhysicsContact *)contact not in
- LINQ .Include() properties from sub-types in TPH i
- Custom Marker performance iOS, crash with result “
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.
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.
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.
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.