Objective-c - Purpose of categories and protocols

后端 未结 5 1076
余生分开走
余生分开走 2020-12-15 01:50

I\'ve been reading up on Objective-c Protocols and Categories and both seem rather pointless to me. They\'re both used for adding things to the program in some funny way ins

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-15 02:26

    Protocols work like interfaces in Java. You can define protocol with some methods and then implement it in many classes. Each of these classes could have different implementation of methods provided by protocol, but the interface would be the same. For example: you want to calculate salary of different types of employees, ex. FullTimeEmployee and ContractEmployee. You can put calculateSalary method definition in protocol and provide different implementations in these two classes, ex. one would return fixed salary while the other would return salary based on worked hours. Then you can cast each class instance to protocol type and invoke given method receiving appropriate results.

    Categories are helpful if you want to extend a class which doesn't belong to you, like in case of built-in classes, ex. NSString. You can add a method like reverse to get reversed string. Why not to make a subclass? Because you can call your custom method on modified class without casting reference to your type.

提交回复
热议问题