Is there any drawback to using C ++ for constants in objective-c

//header-file #import <Foundation/Foundation.h> extern UIColor *const COLOR_BACKGROUND; //implementation-file #import "Constants.h" UIColor *const COLOR_BACKGROUND= [UIColor greenColor]; 

If you try this with the .m file, you will get an error message because it is not a compile-time constant. Changing the implementation file to .mm solves this problem. But are there any quirks I should know about (I'm pretty new to C ++, and I haven't seen anyone do this)?

+4
source share
2 answers

In my opinion, there are two drawbacks:

1. Initialization Procedure

A well-known problem with static initializers in C ++ is the initialization order. This is probably not a big deal when working with colors or fonts. But once you include your own objects, it can quickly become a mess when the constructor of one instance accesses another static object.

2. Objective-C ++ itself

If you use this style, you are bound to Objective-C ++. Not using (pure) Objective-C is inconvenient and error prone when working with other developers or using code from another place. There are many subtle differences between the two languages, and many of them will come and bite you, especially if you are not very experienced with both languages.

There are certain scenarios where you should use Objective-C ++, but I would not use it just for convenience.

+2
source

Arguments against this will be based on style. Functionally, it will work as you expected, and the disadvantages that exist are the same as if you were programming pure C ++ code ...

Quirk you should know about: the wrath of the Objective-C gods and any of your superiors who know Objective-C.

Can I recommend [CIColor colorWithString: (NSString *)] and keep your color constant as NSString as an Objective-C way to accomplish what you want to accomplish. Note that the UIColor class has an initWithCIColor method. You can use this line of logic to create local constant variables for UIColors and calm the marks of Objective-C.

Like SO:

 //.h extern NSString *const COLOR_STRING; //.m NSString *const COLOR_STRING = @"SOME_COLOR"; @implementation ModalDelegate - (id)init { CIColor *const MY_COLOR = [CIColor colorWithString:COLOR_STRING];//Can easily be made a UIColor instead, though unfortunately there is no "UIColor fromString" method. self = [super init]; return self; } 
+1
source

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


All Articles