adit
adit

Reputation: 33644

dynamic binding in objective C

I have a class Topic and Group which both have a variable called 'name', so I am trying to combine these two if statements into one:

if ([((RKMappableObjectTableItem *) _item).object isKindOfClass:[Group class]]){
        Group * group = (Group *)(((RKMappableObjectTableItem *) self.object).object);
       //blah
    } else if ([((RKMappableObjectTableItem *) _item).object isKindOfClass:[Topic class]]){
        Topic * topic = (Topic *)(((RKMappableObjectTableItem *) self.object).object);
       //blah
    }

I tried

id group = (((RKMappableObjectTableItem *) self.object).object);

but when I tried group.name, it gives me:

property name not found on object of type id

Upvotes: 0

Views: 338

Answers (3)

Matthieu Cormier
Matthieu Cormier

Reputation: 2185

You can use a selector to test if an object implements a method before calling that method on the object.

SEL method = @selector(name:);
id groupOrTopic = [((RKMappableObjectTableItem *) self.object) object];

if ([groupOrTopic respondsToSelector:method])
    [groupOrTopic name];

I would not recommend using a base class for both of these objects, I would recommend defining a protocol and having both of these objects implement that protocol if you choose to got that route.

@protocol SomeProtocol
  -(NSString*)name;
@end

Upvotes: 1

sergio
sergio

Reputation: 69027

In Objective-C, properties do undergo a stricter type checking at compile time.

You might want to try:

[group name];

What you do in this case is not using the property mechanism and sending a message to the object. This allow you to fully exploit the dynamic nature of Objective-C.

In this case, you will get a warning, but if you can stand it, it should work fine.

Upvotes: 2

Stephen Darlington
Stephen Darlington

Reputation: 52565

The compiler is correct, group does not have a property called name. group is of type id and not Topic or Group.

Three options:

  1. Cast it
  2. Avoid using dot notation: [group name]
  3. Have a base class common to both Topic and Group that has the name property

Upvotes: 0

Related Questions