在目标c中从id到class的动态类型转换 [英] Dynamic type cast from id to class in objective c

查看:91
本文介绍了在目标c中从id到class的动态类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Objective C中动态转换并访问实例属性.这里是伪代码:

I would like to cast dynamically in Objective C and access instance properties. Here a pseudo code:

id obj;
if (condition1)
    obj = (Class1*)[_fetchedResults objectAtIndex:indexPath.row];
else
    obj = (Class2*)[_fetchedResults objectAtIndex:indexPath.row];

NSNumber *latitude = obj.latitude;

然后,编译器告诉我以下内容: 在类型"__strong id"的对象上找不到纬度"

Then the compiler tells me the following: property 'latitude' not found on object of type '__strong id'

Class1和Class2都是核心数据实体,并且具有几乎相同的属性.在condition1中, _fetchedResults 返回类型为Class1的对象,而在condition2中, _fetchedResults 返回类型为Class2的对象.

Either Class1 and Class2 are core data entities and have nearly the same kind of attributes. In condition1 _fetchedResults returns objects of type Class1 and in condition2 _fetchedResults returns objects of type Class2.

有人可以给我提示如何解决这种问题吗?

Could someone give me a hint how to solve this kind of problem?

谢谢!

推荐答案

您可以通过键值编码(KVC)访问属性:

You can access the properties through Key-Value Coding (KVC):

[obj valueForKey:@"latitude"]

这篇关于在目标c中从id到class的动态类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆