Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to define string constants in an objective-c protocol?

I have defined a protocol that all my plug-ins must implement. I would also like the plug-ins to all use certain strings, like MyPluginErrorDomain. With integers this is quite easily achieved in an enum, but I can't figure out how to do the same with strings. Normally, in classes I would define

extern NSString * const MyPluginErrorDomain;

in the .h file and in the .m file:

NSString * const MyPluginErrorDomain = @"MyPluginErrorDomain";

but that doesn't work very well in a protocol, because then each plug-in would have to provide its own implementation which defeats the purpose of having a constant.

I then tried

#define MYPLUGIN_ERROR_DOMAIN @"MyPluginErrorDomain"

but the implementing classes in the plug-in can't seem to see the #define. Who knows a good solution?

like image 870
Elise van Looij Avatar asked Dec 08 '09 11:12

Elise van Looij


People also ask

How do you define a string constant?

A string constant is enclosed in double quotation marks ("). Any ASCII character is a valid character in a constant string. A block of text defined with the blockdata instruction can also be a string constant.

What is string constant in C with example?

A string constant is an array of characters that has a fixed value enclosed within double quotation marks ( “ “ ). For example, “DataFlair”, “Hello world!”

How do you define a constant string in CPP?

To define a string constant in C++, you have to include the string header library, then create the string constant using this class and the const keyword.


1 Answers

You can declare them in the header with the protocol (but outside the protocol interface itself), then define them in an implementation file for the protocol (obviously it wouldn't have an @implementation section - just your NSString definitions).

Or have a separate .h/.m pair that is just for the string constants (the protocol header can import the string constants header).

like image 92
philsquared Avatar answered Oct 07 '22 01:10

philsquared