Dynamic type cast from id to class in objective c

陌路散爱 提交于 2019-12-23 09:05:34

问题


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;

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

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?

Thanks!


回答1:


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

[obj valueForKey:@"latitude"]



回答2:


The obj variable needs to be of a type that has the property in question. If both entities have the same property, one way to achieve this would be for the property to be declared on a common base class. If it's not appropriate for these two types to share a common base class, then you could have them adopt a common protocol, like this:

@protocol LatitudeHaving
@property (copy) NSNumber* latitude;
@end

@interface Class1 (AdoptLatitudeHaving) <LatitudeHaving>
@end

@interface Class2 (AdoptLatitudeHaving) <LatitudeHaving>
@end

From there, you would declare obj as being an id<LatitutdeHaving>, like this:

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

NSNumber *latitude = obj.latitude;

And that should do it. FWIW, protocols are similar to Interfaces in Java.



来源:https://stackoverflow.com/questions/16299199/dynamic-type-cast-from-id-to-class-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!