When to use categories and when to use subclassing? [closed]

大城市里の小女人 提交于 2019-12-17 21:58:08

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


  • 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.



来源:https://stackoverflow.com/questions/8060884/when-to-use-categories-and-when-to-use-subclassing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!