Creating an abstract class in Objective-C

前端 未结 21 2663
感情败类
感情败类 2020-11-22 15:44

I\'m originally a Java programmer who now works with Objective-C. I\'d like to create an abstract class, but that doesn\'t appear to be possible in Objective-C. Is this poss

21条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 16:30

    Changing a little what @redfood suggested by applying @dotToString's comment, you actually have the solution adopted by Instagram's IGListKit.

    1. Create a protocol for all the methods that make no sense to be defined in the base (abstract) class i.e. they need specific implementations in the children.
    2. Create a base (abstract) class that does not implement this protocol. You can add to this class any other methods that make sense to have a common implementation.
    3. Everywhere in your project, if a child from AbstractClass must be input to or output by some method, type it as AbstractClass instead.

    Because AbstractClass does not implement Protocol, the only way to have an AbstractClass instance is by subclassing. As AbstractClass alone can't be used anywhere in the project, it becomes abstract.

    Of course, this doesn't prevent unadvised developers from adding new methods referring simply to AbstractClass, which would end up allowing an instance of the (not anymore) abstract class.

    Real world example: IGListKit has a base class IGListSectionController which doesn't implement the protocol IGListSectionType, however every method that requires an instance of that class, actually asks for the type IGListSectionController. Therefore there's no way to use an object of type IGListSectionController for anything useful in their framework.

提交回复
热议问题