problem with declare a global variable in objective c

前端 未结 2 1215
一向
一向 2020-12-18 17:05

i have a global variable in 1 of the class like classA.h

const NSString *global;

classA.m

global=[array objectAtIndex:0];/         


        
相关标签:
2条回答
  • 2020-12-18 17:37

    In the header, use:

    extern const NSString *global;
    

    and in the implementation (.m):

    const NSString *global;
    

    The "extern" reference tells all including files that the variable exists, but it's declared elsewhere. Finally, in your implementation file, you put the actual declaration.

    0 讨论(0)
  • 2020-12-18 17:38

    You cannot do this like that.

    const NSString *global;
    NSString const *global;
    

    both mean a pointer (that can be changed) to a constant NSString object. In Objective-C constant objects make no sense. The compiler cannot enforce the constness of objects. It can not know wether a method changes the internal state of an object or not. Also all the classes in the library always take pointers to non-constant objects as parameters for their methods, so having any const object pointers will cause a lot of warnings.

    On the other hand there are constant pointers to objects which are declared like this:

    NSString * const global;
    

    This means the pointer points to a regular NSString object, but it’s value cannot be changed. This means that you also have to initialize the value of the pointer (it cannot be changed later). This is used to define constants. But this only works with NSStrings and string literals. For all other classes there is no way to specify a compile-time constant object thats required for the initialization. And in this case it is a true constant - string literals are immutable by definition.

    But in your case you can do away with the const. You want to change the pointer later so it cannot be a NSString * const. If you insist on a global you’d just have to make it a regular NSString *. On the other hand - globals are evil. You should change your design so you don’t need it.

    0 讨论(0)
提交回复
热议问题