【问题标题】:Passing static object between two class in objective c [duplicate]在目标c中的两个类之间传递静态对象[重复]
【发布时间】:2012-12-28 09:36:46
【问题描述】:

有人知道如何在目标 c 中传递静态对象吗?

在 java 中类似于:

class A {

    static int x;

    ...
}

class B {

    ...

    A.x = 4;

}

类似的东西。

有人知道如何使用 Objective C NSString 实现相同的结果吗?

谢谢。

【问题讨论】:

    标签: objective-c


    【解决方案1】:

    在 Objective-C 中,没有类(静态)变量。您可以做的一件事是使用全局变量,但通常不鼓励这样做:

    // A.h
    extern int x;
    
    // A.m
    int x;
    
    // B.m
    #import "A.h"
    x = 4;
    

    但是,您应该重新考虑您的代码设计,您应该能够在不使用全局变量的情况下摆脱困境。

    【讨论】:

      【解决方案2】:

      您必须在 .m 的顶部声明您的变量,并为静态变量创建一个 getter 和 setter 并使用它

      static int x;
      
      + (int)getX {
          return x;
      }
      
      + (void)setX:(int)newX {
          x = newX;
      }
      

      【讨论】:

        【解决方案3】:

        Objective-C 没有静态/类变量(请注意,静态方法和类方法之间的区别很细微但很重要)。

        相反,您可以在类对象上创建访问器并使用全局静态来存储值:

        @interface MyClass : NSObject
        +(NSString *)thing;
        +(void)setThing:(NSString *)aThing;
        @end
        
        
        
        
        @implementation MyClass
        
        //static ivars can be placed inside the @implementation or outside it.
        static NSString *_class_thing = nil;
        
        +(void)setThing:(NSString *)aThing {
            _class_thing = [aThing copy];
        }
        
        
        +(NSString *)thing {
            return _class_thing;
        }
        
        //...
        @end
        

        【讨论】:

          【解决方案4】:

          在 Obj-C 中没有直接的方法。

          您需要创建一个可以访问静态属性的类方法。

          // class.h
          @interface Foo {
          
          }
          
          +(NSString *) string;
          
          // class.m
          +(NSString *) string
          {
            static NSString *string = nil;
          
            if (string == nil)
            {
              // do your stuff
            }
          
            return string;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-04-03
            • 2020-08-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多