0

Does someone know how to pass static object in objective c ?

In java its something like :

class A {

    static int x;

    ...
}

class B {

    ...

    A.x = 4;

}

something alike.

Someone know how to achieve the same result using Objective C NSString ?

thanks.

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
Dimitri
  • 1,924
  • 9
  • 43
  • 65

4 Answers4

0

In Objective-C, there are no class (static) variables. One thing you can do is to use global variables, but that's generally discouraged:

// A.h
extern int x;

// A.m
int x;

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

However, you should instead rethink your code design, you should be able to get away without using globals.

0

You'll have to declare your variable on the top of your .m and create a getter and setter for the static variable and work with that

static int x;

+ (int)getX {
    return x;
}

+ (void)setX:(int)newX {
    x = newX;
}
Ismael
  • 3,927
  • 3
  • 15
  • 23
0

Objective-C doesn't have static/class variables (note that the difference between static and class methods is subtle but significant).

Instead you can create accessors on the class object and use a global static to store the value:

@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
Benedict Cohen
  • 11,912
  • 7
  • 55
  • 67
0

There is no direct way to do in Obj-C.

You need to create a class-method, that will access the static property.

// class.h
@interface Foo {

}

+(NSString *) string;

// class.m
+(NSString *) string
{
  static NSString *string = nil;

  if (string == nil)
  {
    // do your stuff
  }

  return string;
}
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140