我有一些代码将一个对象分配给通用 id 变量,然后根据该对象所属的类执行各种操作(假设每个类都正确定义和实现了适当的属性):
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;
}
关于 MyClass1 和 MyClass2 片段,是在非动态情况下(属性名称是常量),使用 KVC 是否比直接向对象发送消息更合适或更好?使用 KVC 技术是否会涉及更多开销,因此是否应该仅在调用的属性名称是动态时才使用它?我想了解一下什么时候使用 KVC 是个好主意。
关于 MyClass3 的代码片段 - 为什么使用点语法会导致编译错误?这本质上是不是只是向 getter 访问器发送一条消息,类似于 MyClass1 示例?
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?
发布评论
评论(1)
不,KVC 并不被认为更合适。执行此操作的理想方法是在知道对象是什么后将其强制转换为类类型。您对课程的测试也错误。您应该改用
-isKindOfClass:
。您现在的类测试大致相当于使用-isMemberOfClass:
。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:
.