【问题标题】:Referencing a static NSString * const from another class引用另一个类的静态 NSString * const
【发布时间】:2012-08-10 03:55:44
【问题描述】:

在 A 类我有这个:

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

如何从 B 类中引用它?

【问题讨论】:

    标签: objective-c static constants


    【解决方案1】:

    你应该在标题中extern你的字符串,然后在实现中定义字符串。

    //ClassA.h
    extern NSString * const kMyConstant;
    
    //ClassA.m
    NSString * const kMyConstant = @"my constant string";
    
    //ClassB.h/m
    #import "ClassA.h"
    
    ...
        NSLog(@"String Constant: %@", kMyConstant);
    

    【讨论】:

      【解决方案2】:

      您需要删除static -- 指定kMyConstant 仅在与此链接的文件中可见。

      然后,声明(相对于定义)类 A 的标题中的字符串:

      extern NSString * const kMyConstant;
      

      并将该标头导入您要使用此字符串的任何位置。 extern 声明表明存在一个名为 kMyConstantNSString * const,其存储是在其他地方创建的。

      如果静态定义在标题中已经,则需要将其移动到别处(通常是实现文件)。事物只能定义一次,如果您尝试导入定义变量的文件,您将收到链接器错误。

      【讨论】:

        【解决方案3】:

        如果它是静态的,则不能(这就是 static 关键字的用途)。

        但是,如果您只是将其声明为全局变量,则可以执行以下操作:

        // ClassA.m
        
        NSString *const str = @"Foo";
        
        // ClassB.m
        
        extern NSString *const str;
        
        NSLog(@"str is: %@", str);
        

        【讨论】:

          猜你喜欢
          • 2015-10-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-16
          • 2015-02-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多