Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static array in objective C

I use the following code to create a public static array in C#

public class A{
    public static array[] obj;
}

I have another class B. From class B I call A.ArrayName and I get the array I use in class A.

I wanted to know, what is the equivalent of this in objective C

like image 613
Xavi Valero Avatar asked Dec 08 '11 06:12

Xavi Valero


2 Answers

There is no special syntax for this. You just define a class method to return the static array.

For example:

@implementation A // note this is in the implementation

static NSArray *array;

+ (NSArray *)array
{
  if (!array)
    array = [[NSArray alloc] init];

  return array;
}

@end

Or for messier code, but slightly better performance (a good idea in a tight loop, but usually not worthwhile):

@implementation A

static NSArray *array;

+ (void)initialize // this method is called *once* for every class, before it is used for the first time (not necessarily when the app is first launched)
{
  [super initialize];

  array = [[NSArray alloc] init];
}

+ (NSArray *)array
{
  return array;
}

@end

To access it from class B you just do:[A array]

like image 60
Abhi Beckert Avatar answered Oct 16 '22 10:10

Abhi Beckert


I want to propose using a Category on NSArray. I changed your requirement a bit to use an NSMutableArray as shared object.

interface file:

#import <Foundation/Foundation.h>

@interface NSArray (StaticArray)
+(NSMutableArray *)sharedInstance;

@end

implementation file

#import "NSArray+StaticArray.h"

@implementation NSArray (StaticArray)

+(NSMutableArray *)sharedInstance{

    static dispatch_once_t pred;
    static NSMutableArray *sharedArray = nil;
    dispatch_once(&pred, ^{ sharedArray = [[NSMutableArray alloc] init]; });
    return sharedArray;
}
@end

Now you can use it as:

[[NSArray sharedInstance] addObject:@"aa"];
[[NSArray sharedInstance] addObject:@"bb"];
[[NSArray sharedInstance] addObject:@"cc"];

and somewhere else:

NSLog(@"%@", [NSArray sharedInstance]);
like image 40
vikingosegundo Avatar answered Oct 16 '22 09:10

vikingosegundo