DoK
DoK

Reputation: 871

Dynamic type cast from id to class in 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;

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!

Upvotes: 8

Views: 13472

Answers (2)

ipmcc
ipmcc

Reputation: 29886

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.

Upvotes: 3

Monolo
Monolo

Reputation: 18253

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

[obj valueForKey:@"latitude"]

Upvotes: 7

Related Questions