Im just wondering whether there is a way (in Objective-C and iPad) to call a factory method where I build the name of the object on the fly with a string.
e.g. I have a class XYZ and several factory methods
+(XYZ *) A;
+(XYZ *) B;
+(XYX *) C
I would normally call it like
[XYZ A];
[XYZ B];
[XYZ C];
But I want to be able to call it dynamically with a string e.g.
NSString *s;
...
s = @"B";
[XYZ s];
I hope you get my point.
Thank you.
Yes. You can use
NSSelectorFromString()to convert anNSString*into aSEL(which is the same type that@selector()gives you). You can then call this with-performSelector:and its variants.-performSelector:is useful for methods that take no arguments and returnidorvoid.-performSelector:withObject:and-performSelector:withObject:withObject:are variants that take 1 or 2id-typed parameters. If you need more parameters than that, or you need a parameter or return value that isn’tid, then you can useNSInvocationinstead to set up the method call. Note thatNSInvocationis (relatively) expensive, so it should only be used when there’s no other way.