xceph
xceph

Reputation: 1046

Determine class of an object from id<protocol>

I have a class like so:

@interface Foo : NSObject <FooDataProvider>
...
@end

and somewhere along the line in another class I have a method with the interface:

-(void) doStuff:(id<FooDataProvider>)fooProvider{
...
}

And yet somwhere else I have

-(void) passMeClasses:(Class)theClass
{
<do stuff based on the class>
}

Usually I pass things to this method simply like

Foo* f = [[Foo alloc] init];
...
[bar passMeClasses:[f class]];

But Im not sure how to pass things I only have the id.. like so

id<FooDataProvider> f = [[Foo alloc] init];
....
[bar passMeClasses:[f ?????]];

or alternatively how to do it from the doStuff method

-(void) doStuff:(id<FooDataProvider>)fooProvider{
  Class c = [fooProvider howDoIGetMyClass];
  bar passMeClasses:c];
}

Can someone help me in determining the class from the id?

Sorry for the long winded explanation, but hopefully its clear!

Upvotes: 1

Views: 59

Answers (1)

Rob Napier
Rob Napier

Reputation: 299585

[f class]

class is a method. It's called on the object. The object will return its class (or it should; it can technically return something else and sometimes does). The type of the variable is completely irrelevant at runtime. At runtime all object pointers are id. That's why method signature type encodings only designate "an object goes here." (See @.) They can't express the specific type of the object.

Upvotes: 1

Related Questions