How do I dynamically define an instance variable?

Posted by Moses on Stack Overflow See other posts from Stack Overflow or by Moses
Published on 2010-04-25T15:09:35Z Indexed on 2010/04/25 15:13 UTC
Read the original article Hit count: 206

Filed under:

Hi everyone,

I have two classes (class1 and class2) that just store data, no methods. I have a third class that has an instance variable that, depending on some user input, will be set to one of the two classes. So, in the third class I declare the variable generically as

NSObject *aClass;

and during runtime set it to whatever it should be.

aClass = [[Class1 alloc] init]; // or 
aClass = [[Class2 alloc] init];

However, when I try to access fields from aClass

NSString *str = aClass.field1;

It gives me the error: request for member 'field1' in something not a structure or a union. Field1 is declared in both class1 and class2. When I try to cast aClass

aClass = (Class1 *) aClass;

it gives the same error. What am I doing wrong, is there a better way to do this?

© Stack Overflow or respective owner

Related posts about objective-c