CalZone
CalZone

Reputation: 1721

Objective-C Check if self also a subclass

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 make a check in classA, whether or not self is a ClassB or ClassC.

Upvotes: 5

Views: 2853

Answers (4)

Vasiliy Ivanov
Vasiliy Ivanov

Reputation: 11

My solution in one string is:

//Do not use this class. Use subclass instead ASSERT([NSStringFromClass([self class]) isEqualToString:@"SDDocumentsViewController"]==NO);

Upvotes: 0

Caleb
Caleb

Reputation: 125037

I need to make a check in classA, whether or not self is a ClassB or ClassC.

A better way to do that is to call some abstract method that can be defined in your subclasses:

ClassA:

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

- (void)doSpecializedThing
{
    return;
}

ClassB:

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

ClassC:

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

This prevents ClassA from having to know anything specific about its subclasses, as that's pretty much always a bad idea.

You can also override -doThing in ClassB and ClassC and have them call [super doThing] in their implementation. That's not necessarily the right solution in every case, though, such as when the code in ClassA's -doThing relies on some behavior in the subclasses (e.g. if -doSpecializedThing were to return a value used in -doThing).

Upvotes: 5

lakshmen
lakshmen

Reputation: 29094

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

}

Hope this helps...

As H2CO3 said, bring that subclass specific behavior into the subclass itself.

Upvotes: 2

user529758
user529758

Reputation:

I need to...

No, you don't. If a base class requires knowledge about its subclasses, then you have made a huge design mistake.


Anyway, this is how to check for being in a specific subclass:

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

Upvotes: 26

Related Questions