Dynamic type cast from id to class in objective c

DoK picture DoK · Apr 30, 2013 · Viewed 11.5k times · Source

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!

Answer

Monolo picture Monolo · Apr 30, 2013

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

[obj valueForKey:@"latitude"]