views:

197

answers:

3

Is it possible to create an object named after an NSString's value? If so, how?

+3  A: 

Try this:

Class theClass = NSClassFromString(someString);
id object = [[theClass alloc] init];
Matt Ball
+1  A: 

If you mean that the string specifies the class name, then yes it's easy to do this using the NSClassFromString function to lookup the appropriate class "factory" object:

NSString* myClassName = @"NSNumber";
id myNewObject = [[NSClassFromString(myClassName) alloc] init];

// myNewObject is an NSNumber...

The example is contrived, but you get the idea.

danielpunkass
+1  A: 

Yes:

//In your header
extern NSString *FrobnitzerCalibrationHigh;
extern NSString *FrobnitzerCalibrationMedium;
extern NSString *FrobnitzerCalibrationLow;

//In your implementation
NSString *FrobnitzerCalibrationHigh = @"FrobnitzerCalibrationHigh";
NSString *FrobnitzerCalibrationMedium = @"FrobnitzerCalibrationMedium";
NSString *FrobnitzerCalibrationLow = @"FrobnitzerCalibrationLow";

You can make a couple of macros and put them in your prefix header:

//Semicolons intentionally omitted (see below)
#define DECLARE_STRING_CONSTANT(name) extern NSString *name
#define DEFINE_STRING_CONSTANT(name) NSString *name = @#name

Then use them in your class headers and implementations:

//In your header
DECLARE_STRING_CONSTANT(FrobnitzerCalibrationHigh);
DECLARE_STRING_CONSTANT(FrobnitzerCalibrationMedium);
DECLARE_STRING_CONSTANT(FrobnitzerCalibrationLow);

//In your implementation
DEFINE_STRING_CONSTANT(FrobnitzerCalibrationHigh);
DEFINE_STRING_CONSTANT(FrobnitzerCalibrationMedium);
DEFINE_STRING_CONSTANT(FrobnitzerCalibrationLow);

(The macros omit the semicolons because their usages will supply them. If the macros had semicolons as well, the expansion would be extern NSString *FrobnitzerCalibrationHigh;;—harmless in this case, but it would bug me if I did this, largely because it's not harmless in some other cases.)

Peter Hosey