How can I check a specific macro there or not with an identifier stored inside an NSString

I have macros named

CONSTANT_1 CONSTANT_2 CONSTANT_3 CONSTANT_4 etc.. 

I have an NSString variable sent from another class consisting only of a macro name, how can I access the contents of the macro variable corresponding to this NSString.

My NSString variable is defined as:

 NSString * str=@ "CONSTANT_3" 
+6
source share
2 answers

1 Here is one solution for this, but you need to know all the 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 like:

 int constVal = [ClassName getValueForContant:@"CONSTANT_1"]; 

As a result, you get the value int .

2 Use .plist to determine the constants and run the loop to get the appropriate value as the provided string parameter to this method;

 + (int)getValueForContant:(NSString *)constantStr 
+4
source

I would recommend using constants better

 NSString *const CONSTANT_1 = @"1"; NSString *const CONSTANT_2 = @"2"; NSString *const CONSTANT_3 = @"3"; 

You can use CFBundleGetDataPointerForName

 -(NSString *)valueOfConstantWithName:(NSString *)constantName { void ** pointer = CFBundleGetDataPointerForName(CFBundleGetMainBundle(), (__bridge CFStringRef)constantName); return (__bridge NSString *)(pointer ? *pointer : nil); } 

and use this method e.g.

 NSString *costant1 = [self valueOfConstantWithName:@"CONSTANT_1"]; 
+1
source

Source: https://habr.com/ru/post/1013722/


All Articles