Distinguish instance and class

Basically, my problem is this:

-(void)aMethod:(id)object;

Ideally, I would use my method as follows:

NSObject*theObject;
[MysteryObject aMethod:theObject];

or like this:

[MysteryObject aMethod:NSObject];

In principle, this is a question. How to distinguish the variable 'id' simply from the type of the class or pointer to a living object?

+3
source share
2 answers

This should work:

if ([MysteryObject respondsToSelector:@selector(isSubclassOfClass:)])
    NSLog(@"is a class");
else
    NSLog(@"is an object");

But in fact, to be more duck-friendly, you should probably use respondsToSelectorto verify the message you are about to send.

+2
source

Although using executable functions is fine, I find this a much simpler way to achieve the same result:

- (void) aMethod:(id)anObject
{
  if( anObject == [anObject class] ) {
    // the object is a class
  }
  else {
    // the object is an instance object
  }
}
0
source

All Articles