Abstract class for Objective-C

Possible duplicate:
Creating an abstract class in Objective-C

I would like to make an abstract class in an Objective-C project.

But I can not find such ideas as "abstract" (in java), "virtual" (in C ++).

Does Objective-C have an abstract idea? Thanks.

0
source share
2 answers

Formally, no. Abstract classes are implemented by creating methods in the base class, and then documenting that the subclass should implement these methods. The responsibility of the author is to write classes that match the class contract, not the compiler, to test for missing methods.

Objective-C has protocols that are similar to Java interfaces. If you are looking for the equivalent of a pure C ++ virtual class or interface in Java, this is what you want.

+7
source

There are no abstract classes, but you can create something similar using a combination of class and protocol (which is similar to the Java interface). First, divide your abstract class into those methods that you want to provide default implementations, and those that you need to implement subclasses. Now declare the default methods in @interface and implement them in @implementation and declare the necessary methods in @protocol . Finally, you get subclasses from class<protocol> - a class that implements the protocol. For instance:

 @interface MyAbstract - (void) methodWithDefaultImplementation; @end @protocol MyAbstract - (void) methodSubclassMustImplement; @end @implementation MyAbstract - (void) methodWithDefaultImplementation { ... } @end @interface MyConcreteClass: MyAbstract<MyAbstract> ... @end @implementation MyConcreteClass // must implement abstract methods in protocol - (void) methodSubclassMustImplement { ... } @end 

If you are worried about using the same name for the class and looking at the protocol in Cocoa, where NSObject follows this pattern ...

NTN

+11
source

All Articles