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
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]
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With