简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM