Objective-C Is it safe to overwrite [NSObject initialize]?

后端 未结 3 751
悲&欢浪女
悲&欢浪女 2020-12-17 02:55

Basically, I have the following code (explained here: Objective-C Constants in Protocol)

// MyProtocol.m
const NSString *MYPROTOCOL_SIZE;
const NSString *MYP         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-17 03:32

    A variable of type NSString *const will always be initialized before your code runs, assuming we ignore C++ vagaries for the moment:

    NSString *const MY_PROTOCOL_SIZE = @"...";
    

    A variable of type const NSString * (the const keyword applying to the guts of the NSString, not its address) can be modified by any code, but cannot have messages sent to it. It defeats the purpose of making it const. Consider instead a global function:

    static NSString *GetMyProtocolSize(void) {
        return [[MyClass someStringLoadedFromAFile] ...];
    }
    

    Or use a class method:

    @implementation MyClass
    + (NSString *)myProtocolSize {
        return [[MyClass someStringLoadedFromAFile] ...];
    }
    @end
    

    You asked a question earlier about why your const strings wouldn't accept dynamic values--this is because you do not seem to understand what const does to a symbol. You should read up on the meaning of the const keyword in C and should look at another approach to getting your strings if const is not the right one.

提交回复
热议问题