2

I have some data in a database I want to retrieve as an NSArray of custom objects, and I want this NSArray to be static, since I need it to be referenced from a class whose methods are all class methods and I don't instantiate. I'll need to first check if this NSArray already contains objects and, if not, get the data from the database and create it. Then, I'd need to be able to get this NSArray from a view controller, something like NSArray *listOfItems = [MyClass getStaticArray], but I don't know how to handle this.

Another question related to this: what memory management implications would it have such static NSArray?

Thanks!

AppsDev
  • 12,319
  • 23
  • 93
  • 186
  • 1
    Several others have already mentioned the singleton pattern; the memory management implications of that pattern are that the array will never be deallocated until the process exits, but there will (typically) only be one copy of the array, so this is usually not an issue for static data. – ipmcc Aug 01 '13 at 14:44
  • possible duplicate of [Objective C Static Class Level variables](http://stackoverflow.com/questions/1063229/objective-c-static-class-level-variables) – jscs Aug 01 '13 at 19:03

2 Answers2

1

The best solution in your case, based on what you've described, would be to use the Singleton Pattern. Make sure that you understand it. Here is a StackOverflow question regarding Singleton on iOS.

Community
  • 1
  • 1
Bruno Koga
  • 3,864
  • 2
  • 34
  • 45
1

Just use Singleton.

Create class StaticArrayClass : NSArray

And then in .m file:

+(id)sharedInstance {
    static dispatch_once_t pred;
    static StaticArrayClass *sharedInstance = nil;
    dispatch_once(&pred, ^{
        sharedInstance = [[StaticArrayClass alloc] initWithArray:@[@1,@2.....]];
    });
    return sharedInstance;
}

- (void)dealloc {
    abort();
}

In .h file:

@interface StaticArrayClass : NSArray

+(id)sharedInstance;

And that's it.

You can call it like:

NSArray *listOfItems = [StaticArrayClass sharedInstance]

Anywhere in your application. If you're don't know singleton design pattern please visit link in @Bruno Koga answer.

Jakub
  • 13,712
  • 17
  • 82
  • 139