Constants in Objective-C

后端 未结 14 1282
广开言路
广开言路 2020-11-21 22:10

I\'m developing a Cocoa application, and I\'m using constant NSStrings as ways to store key names for my preferences.

I understand this is a good idea b

14条回答
  •  不思量自难忘°
    2020-11-21 22:39

    I am generally using the way posted by Barry Wark and Rahul Gupta.

    Although, I do not like repeating the same words in both .h and .m file. Note, that in the following example the line is almost identical in both files:

    // file.h
    extern NSString* const MyConst;
    
    //file.m
    NSString* const MyConst = @"Lorem ipsum";
    

    Therefore, what I like to do is to use some C preprocessor machinery. Let me explain through the example.

    I have a header file which defines the macro STR_CONST(name, value):

    // StringConsts.h
    #ifdef SYNTHESIZE_CONSTS
    # define STR_CONST(name, value) NSString* const name = @ value
    #else
    # define STR_CONST(name, value) extern NSString* const name
    #endif
    

    The in my .h/.m pair where I want to define the constant I do the following:

    // myfile.h
    #import 
    
    STR_CONST(MyConst, "Lorem Ipsum");
    STR_CONST(MyOtherConst, "Hello world");
    
    // myfile.m
    #define SYNTHESIZE_CONSTS
    #import "myfile.h"
    

    et voila, I have all the information about the constants in .h file only.

提交回复
热议问题