3

Basically, my problem is this:

-(void)aMethod:(id)object;

Ideally, I would use my method like this:

NSObject*theObject;
[MysteryObject aMethod:theObject];

or like this:

[MysteryObject aMethod:NSObject];

Basically, that is the question. How can I distinguish if an 'id' variable holds simply a Class type or a pointer to a live object?

Sebastian
  • 7,670
  • 5
  • 38
  • 50
  • 1
    Objective-C and C aren't related like this...the `C` tag should be taken off. – Jon Egeland May 09 '12 at 20:38
  • It's a pretty clear question - I don't know why it's being voted for closing. – Mahmoud Al-Qudsi May 09 '12 at 20:50
  • 1
    The second code snippet should read `[MysteryObject aMethod:[NSObject class]];`, otherwise it would be a compilation error. – Lvsti May 09 '12 at 20:50
  • 1
    I have answered this question here: [Check if object is Class type](http://stackoverflow.com/questions/6536244/check-if-object-is-class-type/6537756#6537756) – Joe May 09 '12 at 20:59

2 Answers2

2

This should work:

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

But in fact, to be more duck type friendly, you should probably use respondsToSelector to check for the message you're actually going to send.

Per Johansson
  • 6,697
  • 27
  • 34
  • This should work, but it will need to be called like this: `[MysteryObject aMethod:[NSObject class]]` when giving it a class rather than an object. – UIAdam May 09 '12 at 20:54
0

Although using runtime functions is perfectly fine, I believe this is 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
  }
}
Dave FN
  • 652
  • 1
  • 14
  • 29