Reputation: 1941
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.
Upvotes: 1
Views: 86
Reputation: 185861
Yes. You can use NSSelectorFromString()
to convert an NSString*
into a SEL
(which is the same type that @selector()
gives you). You can then call this with -performSelector:
and its variants.
[XYZ performSelector:NSSelectorFromString(s)];
-performSelector:
is useful for methods that take no arguments and return id
or void
. -performSelector:withObject:
and -performSelector:withObject:withObject:
are variants that take 1 or 2 id
-typed parameters. If you need more parameters than that, or you need a parameter or return value that isn't id
, then you can use NSInvocation
instead to set up the method call. Note that NSInvocation
is (relatively) expensive, so it should only be used when there's no other way.
Upvotes: 2