Objective C Macro append to string

后端 未结 3 1500
隐瞒了意图╮
隐瞒了意图╮ 2021-01-25 12:58

I think this is a very simple thing to do, but since I\'m new to iOS development and objective C, I can\'t figure it out.

#define RESTFUL_PATH_PREFIX @\"https://         


        
3条回答
  •  隐瞒了意图╮
    2021-01-25 13:33

    Since I made this answer to a question marked as a dupe, I'll also answer it here


    Sure, you can use defines OR you can use NSString constants. It's really a matter of preference ... I have however seen both a #define and an NSString const * const being used before. Defines are easier, and you're probably not going to save that much memory by having constants instead of individual immutable instances of NSString all over the place.

    Some advice is to think about how you export the NSString constants. You'll probably want EXTERN_PRIVATE instead of EXTERN, but my sample code will allow all clients of your header to read the string constants you've declared therein.

    What you can do:

    1. Create a new .m/.c file with a header in Xcode
    2. In the .m/.c file, declare and initialise your constants
    3. Export the constant as necessary so other compilation units can access it

    constants.h

    #ifndef constants_h
    #define constants_h
    
    // Export the symbol to clients of the static object (library)
    #define EXTERN extern __attribute__((visibility("default")))
    // Export the symbol, but make it available only within the static object
    #define EXTERN_PRIVATE extern __attribute__((visibility("hidden")))
    // Make the class symbol available to clients
    #define EXTERN_CLASS __attribute__((visibility("default")))
    // Hide the class symbol from clients
    #define EXTERN_CLASS_PRIVATE __attribute__((visibility("hidden")))
    #define INLINE static inline
    
    #import 
    
    EXTERN NSString const * _Nonnull const devBaseUrl;
    
    #endif /* constants_h */
    

    constants.m

    #include "constants.h"
    
    NSString const * _Nonnull const devBaseUrl = @"http://127.0.0.1:8000/";
    

    main.m

    #import 
    #import "constants.h"
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            NSLog(@"Constant value: %@", devBaseUrl);
            // Prints: Constant value: http://127.0.0.1:8000/
        }
        return 0;
    }
    

提交回复
热议问题