Referencing a static NSString * const from another class

前端 未结 3 499
闹比i
闹比i 2020-12-10 01:27

In class A I have this:

static NSString * const kMyConstant = @\"my constant string\";

How can I reference this from class B?

相关标签:
3条回答
  • 2020-12-10 01:48

    You should extern your string in the header, and then define the string in the implementation.

    //ClassA.h
    extern NSString * const kMyConstant;
    
    //ClassA.m
    NSString * const kMyConstant = @"my constant string";
    
    //ClassB.h/m
    #import "ClassA.h"
    
    ...
        NSLog(@"String Constant: %@", kMyConstant);
    
    0 讨论(0)
  • 2020-12-10 02:01

    You need to remove the static -- that specifies that kMyConstant is only visible in files linked with this one.

    Then, declare (as opposed to defining) the string in Class A's header:

    extern NSString * const kMyConstant;
    

    and import that header wherever you want to use this string. The extern declaration says that there exists an NSString * const by the name kMyConstant whose storage is created in some other place.

    If the static definition is already in the header, you need to move it elsewhere (usually the implementation file). Things can only be defined once, and if you try to import a file which defines a variable, you'll get a linker error.

    0 讨论(0)
  • 2020-12-10 02:08

    If it's static, you can't (that's what the static keyword is for).

    If you simply declare it as a global variable, however, you can do something like this:

    // ClassA.m
    
    NSString *const str = @"Foo";
    
    // ClassB.m
    
    extern NSString *const str;
    
    NSLog(@"str is: %@", str);
    
    0 讨论(0)
提交回复
热议问题