我想在Objective C中动态转换并访问实例属性.这里有一个伪代码:
- id obj;
- if (condition1)
- obj = (Class1*)[_fetchedResults objectAtIndex:indexPath.row];
- else
- obj = (Class2*)[_fetchedResults objectAtIndex:indexPath.row];
- NSNumber *latitude = obj.latitude;
然后编译器告诉我以下内容:
在’__strong id’类型的对象上找不到属性’latitude’
Class1和Class2都是核心数据实体,具有几乎相同的属性.在condition1中_fetchedResults返回Class1类型的对象,在condition2中_fetchedResults返回Class2类型的对象.
谢谢!
解决方法
您可以通过键值编码(KVC)访问属性:
- [obj valueForKey:@"latitude"]