Can Objective-C protocols and categories be inherited?

后端 未结 5 1732
名媛妹妹
名媛妹妹 2020-12-30 03:13

I am little confused about some concepts around Objective-C protocols and categories.

Can protocols and categories be inherited by subclasses in Objective-C?

5条回答
  •  被撕碎了的回忆
    2020-12-30 03:38

    Protocols are like interfaces in Java. So, a class provides a protocol for accessing it.

    You can "subclass" protocols just like in Java you can "subclass" interfaces.

    Categories on the other hand are a way to add more methods to a class. The restriction is you can't add any instance variables with a category. You can only access the existing instance variables.

    It's very useful though because it avoids creating a large fragile subclass hierarchy.

    So, bottom line is, if you want a view different classes to conform to a standard interface, then use a protocol. If you want to add a few methods to an existing class without the hassle of subclassing, go for a category.

    However, one thing to bear in mind is that when you add methods to a category - something I've been reminded of by workmates - is that you're making those methods available everywhere. I've read in a few places that a common newbie mistake is to go crazy with categories, using them all the time instead of creating new classes that would do the job.

    So, if the new category method that you're considering is really specific or rather - tightly coupled - to a business function, then probably it shouldn't be a category. They really should only be used for generic additions to the base class.

提交回复
热议问题