Dynamic type discarded from id to class in object c

I would like to dynamically add instance object properties to Objective-C. Here's the 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: the property 'latitude' was not found on an object of type '__strong id'

Either Class1 and Class2 are the main data objects and have almost the same attributes. In condition1, _fetchedResults returns objects of type Class1 and in condition2 _fetchedResults returns objects of type Class2.

Can someone give me a hint how to solve this problem?

Thanks!

+7
source share
2 answers

You can access properties using Keyword Coding (KVC):

 [obj valueForKey:@"latitude"] 
+4
source

The obj variable must have a type that has the corresponding property. If both objects have the same property, one way to achieve this would be to declare the property in a common base class. If a common common class is not suitable for these two types, you can force them to accept a common protocol, for example:

 @protocol LatitudeHaving @property (copy) NSNumber* latitude; @end @interface Class1 (AdoptLatitudeHaving) <LatitudeHaving> @end @interface Class2 (AdoptLatitudeHaving) <LatitudeHaving> @end 

From there, you will declare obj as id<LatitutdeHaving> , for example:

 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 Java interfaces.

+1
source

All Articles