When to use categories and when to use subclassing

2019-01-21 17:12发布

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.

4条回答
成全新的幸福
2楼-- · 2019-01-21 17:25

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.

查看更多
看我几分像从前
3楼-- · 2019-01-21 17:28

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.

查看更多
祖国的老花朵
4楼-- · 2019-01-21 17:35
  • 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.

查看更多
Ridiculous、
5楼-- · 2019-01-21 17:36

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.

查看更多
登录 后发表回答