Reputation: 2488
I'm very new in objective C and i want to know if/how what i would like to do is possible. I have a few classes
@interface A: NSObject
{
NSString* Aa;
NSUInteger Ab;
}
@interface B: A
{
NSString* Ba;
NSUInteger Bb;
}
@interface C: A
{
NSString* Ca;
NSUInteger Cb;
}
I want to create a function where i expect 'A' type of object and in the implementation check if their type is B or C later. Here's what i want:
-(void)doSomething:(A *param)
{
//do some stuff
if(param is an instance of B)
{
//do stuff with B
}
else
{
//do stuff with C
}
}
How can it be done?
Sincerely,
Zoli
Upvotes: 3
Views: 3306
Reputation: 1442
There's four methods you might want to use:
isKindOfClass:
tests if an object is a member of class or subclassisMemberOfClass:
same as above, but more specific, doesn't allow subclassesrespondsToSelector:
test if an object responds to a given selector, like [param respondsToSelector:@selector(method:)]
. Useful for duck typing.conformsToProtocol:
test if object implements a protocol.Upvotes: 6
Reputation: 2417
Check NSObject's method isKindOfClass:(Class)c You would do this:
-(void)doSomething:(A *)param
{
//do some stuff
if([param isKindOfClass:[B class]])
{
//do stuff with B (cast will be required to avoid warnings!)
B *castedB = (B *)param;
//...
}
else if ([param isKindOfClass:[C class]])
{
//do stuff with C
C *castedC = (C *)param;
//...
}
}
Hope this help!
Upvotes: 6