I have macros named
CONSTANT_1 CONSTANT_2 CONSTANT_3 CONSTANT_4 etc..
I have an NSString variable sending from another class consist of macro name only, how can I access the contents of macro variable matching with this NSString.
My NSString variable is defined as:
NSString *str=@"CONSTANT_3"
2 Answers
Answers 1
1 Here is one solution to do it, but it needs you to know all macros:
#define CONSTANT_1 1 #define CONSTANT_2 2 #define CONSTANT_3 3 #define STRINGIZE(x) #x + (int)getValueForContant:(NSString *)constantStr { const char *charStr = STRINGIZE(CONSTANT_1); NSString *str = [NSString stringWithUTF8String:charStr]; if ([constantStr isEqualToString:str]) { return CONSTANT_1; } charStr = STRINGIZE(CONSTANT_2); str = [NSString stringWithUTF8String:charStr]; if ([constantStr isEqualToString:str]) { return CONSTANT_2; } return -1; }
And use it as:
int constVal = [ClassName getValueForContant:@"CONSTANT_1"];
It'll give you int
value in return.
2 Use .plist
to define constants and loop through to get appropriate value as provided string parameter to this method;
+ (int)getValueForContant:(NSString *)constantStr
Answers 2
I would recommend to better use constants
NSString *const CONSTANT_1 = @"1"; NSString *const CONSTANT_2 = @"2"; NSString *const CONSTANT_3 = @"3";
The you could use CFBundleGetDataPointerForName
-(NSString *)valueOfConstantWithName:(NSString *)constantName { void ** pointer = CFBundleGetDataPointerForName(CFBundleGetMainBundle(), (__bridge CFStringRef)constantName); return (__bridge NSString *)(pointer ? *pointer : nil); }
and use that method like
NSString *costant1 = [self valueOfConstantWithName:@"CONSTANT_1"];
0 comments:
Post a Comment