I have some code that assigns an object to a generic id variable and then does various things depending on the class to which said object belongs (assume that each class has the appropriate property defined and implemented correctly):
id obj = #<this could be one of several things>#
id result;
if ([obj class] == [MyClass1 class])
{
result = [obj myProp1];
}
else if ([obj class] == [MyClass2 class])
{
result = [obj valueForKey:@"myProp2"];
}
else if ([obj class] == [MyClass3 class])
{
result = obj.myProp3; // this doesn't compile!
}
else
{
result = nil;
}
Regarding the MyClass1 and MyClass2 snippets, is using KVC considered more proper or better than just sending the message to the object directly in non-dynamic cases (name of property is constant)? Does using the KVC technique involve more overhead, thus should it only be used when the name of the property that gets invoked is dynamic? I would like to get a feel for when it is a good idea to use KVC.
Regarding the snippet with MyClass3- why does using the dot syntax cause a compilation error? Isn’t this essentially just sending the getter accessor a message, similar to the the MyClass1 example?
No, KVC is not considered more proper. The ideal way to do this is to cast your object to the class type once you know what it is. You’re also testing the class wrong. You should be using
-isKindOfClass:instead. Your class test right now is roughly equivalent to using-isMemberOfClass:.