Objective-C Check if I'm a subclass too

This is in context with Objective C. I have 3 classes. ClassA , ClassB and ClassC .

ClassB and ClassC are subclasses of ClassA .

 @interface ClassB : ClassA @interface ClassC : ClassA 

I need to check ClassA , regardless of whether it is self ClassB or ClassC .

+4
source share
4 answers

I need...

No, you do not. If the base class requires knowledge of its subclasses, you have made a huge design mistake.


In any case, this is how to check for a specific subclass:

 if ([self isKindOfClass:[ClassB class]]) { // Class B } else if ([self isKindOfClass:[ClassC class]]) { // Class C } 
+23
source

I need to do a check in class A, regardless of whether I myself am ClassB or ClassC.

The best way to do this is to call an abstract method that can be defined in your subclasses:

ClassA:

 - (void)doThing { [self doSpecializedThing]; } - (void)doSpecializedThing { return; } 

ClassB:

 - (void)doSpecializedThing { // ClassB specialized version of whatever ClassA needs to do } 

ClassC:

 - (void)doSpecializedThing { // ClassC specialized version of whatever ClassA needs to do } 

This prevents ClassA from knowing anything specific about its subclasses, as it is almost always a bad idea.

You can also override -doThing in ClassB and ClassC and call them [super doThing] in your implementation. This is not necessarily the right decision in every case, although, for example, when the code in ClassA -doThing relies on some behavior in subclasses (for example, if -doSpecializedThing should return the value used in -doThing ).

+5
source
 if([self isKindOfClass:[ClassB class]]){ ... } else if ([self isKindOfClass:[ClassC class]]) { } 

Hope this helps ...

As stated in H2CO3, bring the specific behavior of the subclass to the subclass itself.

+2
source

My solution in one line:

// Do not use this class. Instead, use a subclass of ASSERT ([NSStringFromClass ([self class]) isEqualToString: @ "SDDocumentsViewController"] == NO);

0
source

All Articles