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!

2
  • 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. Commented Aug 1, 2013 at 14:44
  • possible duplicate of Objective C Static Class Level variables Commented Aug 1, 2013 at 19:03

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.