I want to construct a method which returns as a string the class prefix of the module it is operating in.
For example, if I have project with classes named XYZMessage
, XYZBusiness
, XYZTransaction
... I want a function to return the string XYZ
.
I have an implementation which uses the name of the appDelegate (The first capital letters except the last) to do this, but I would like a better way. I would hope that Xcode defines a macro with this value or there's a key in the plist or something more concrete. I don't want to #define CLASS_PREFIX @"XYZ"
or anything hard-coded.
EDIT: The Why
The situation is I have a server who provides me the type (i.e. which class to construct) along with the information.
{
"type" : "merchant",
"data" : {
"name" : "Super cool pizza",
"location" : {
"lat" : "123.000",
"lon" : "23.0000"
}
}
I have a class AXQMerchant
which will take this (data) payload as it's initializer (unpack the keys/values, match the types to its properties, build sub-objects, etc.)
What I'm trying to avoid is this structure in my API handler:
NSString* objectType = ...; //server provided
NSString* classToConstruct; //our local type
if ([objectType isEqualToString:@"transaction"]) {
classToConstruct = @"AXQTransaction";
} else if ([objectType isEqualToString:@"store"]) {
classToConstruct = @"AXQStore";
... //a series of else-if blocks
} else if ([objectType isEqualToString:@"merchant"]) {
classToConstruct = @"AXQMerchant";
}
id object = [[NSClassFromString(classToConstruct) alloc] initWithPayload:...];
//now do something with object
This section will easily grow unwieldy when my type list is >20 types. What I want to write is:
classToConstruct = [classPrefix() stringByAppendingString:[objectType capitalizedString]];
id object = [[NSClassFromString(classToConstruct) alloc] initWithPayload:...];
For those who are curious; my current implementation is...
str = NSStringFromClass([[UIApplication sharedApplication].delegate class]); //could be [self class], instead...
for (NSUInteger i = 0; i < str.length; i++) {
unichar c = [str characterAtIndex:i];
if (c < 'A' || c > 'Z') { //if c is not a capital we're at prefix end (+1 extra)
return [str substringWithRange:NSMakeRange(0, i - 1)];
}
}
return nil;
This is dispatch_once()
'd so I only calculate it when the app is opened the first time.