static NSString usage vs. inline NSString constants

前端 未结 6 666
独厮守ぢ
独厮守ぢ 2021-01-30 09:03

In Objective-C, my understanding is that the directive @\"foo\" defines a constant NSString. If I use @\"foo\" in multiple places, the same immutable NSString object is referenc

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-30 09:17

    I love all the answers here without a simple example of how to correctly declare one... so...

    If you want the constant to be externally visible (ie. "global").... declare it as such in a header...

    extern NSString *const MyTypoProneString;

    and define it in a .m file, OUTSIDE any @implementation like...

    NSString * const MyTypoProneString = @"iDoNtKnOwHoW2tYpE";

    That said... if you simply want a static const that IS LOCAL to your class' implementation (or even a certain method!)... simply declare the string INSIDE the implementation (or method) as...

    static NSString *MavisBeacon = @"She's a freakin' idiot";

    EDIT Although I do show how to do this... I have yet to be convinced that this style is in any way better than the ridiculously shorter, simpler, and less repetitive SINGLE declaration, á la..

    #define SomeStupidString @"DefiningConstantsTwiceIsForIdiots"
    

    Use #define's... they are way less annoying.. Just don't let the preprocessor-player-haters get you down.

提交回复
热议问题