Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Static NSMutableArray in a class in Objective c?

I have Class A which is super class for both class B and class C. I need to store the objects of Class A in 'static' NSMutablearray defined in Class A. Is it possible to modify data stored in MSMutableArray using methods in Class B and Class C? How to create and initialize Static array? An example would be of more help. thanks in advance.

like image 460
Ka-rocks Avatar asked Oct 06 '10 10:10

Ka-rocks


1 Answers

Here is one way to do it.

@interface ClassA : NSObject
{
}

-(NSMutableArray*) myStaticArray;

@end

@implementation ClassA

-(NSMutableArray*) myStaticArray
{
    static NSMutableArray* theArray = nil;
    if (theArray == nil)
    {
        theArray = [[NSMutableArray alloc] init];
    }
    return theArray;
}

@end

That is a pattern I use quite a lot instead of true singletons. Objects of ClassA and its subclasses can use it like this:

[[self myStaticArray] addObject: foo];

There are variations you can consider e.g. you can make the method a class method. You might also want to make the method thread safe in a multithreaded environment. e.g.

-(NSMutableArray*) myStaticArray
{
    static NSMutableArray* theArray = nil;
    @synchronized([ClassA class])
    {
        if (theArray == nil)
        {
            theArray = [[NSMutableArray alloc] init];
        }
    }
    return theArray;
}
like image 130
JeremyP Avatar answered Sep 20 '22 05:09

JeremyP