Reputation: 29896
Is it possible in Objective C to modify an object type at runtime without the compiler complaining?
e.g.
id object;
in an init method
initWithType:(someEnumType) type
then depending on type set the object to a class type.
How is this done without the compiler flagging errors that object does not declare someMethod?
Upvotes: 1
Views: 64
Reputation: 726599
The most common way to do something like that is in a factory method, rather than an initializer:
typedef enum {
etString,
etNumber
} EnumType;
@implementation MyFactory
+(id)makeNewObjectWithType:(EnumType)et {
id res;
switch (et) {
case etString:
res = [NSString string];
break;
case etNumber:
res = [NSNumber numberWithInt:12345];
break;
default:
res = nil;
break;
}
return res;
}
@end
Upvotes: 1