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
This is a sample that I use quite a lot, not real singletones. ClassA objects and its subclasses can use it as follows:
[[self myStaticArray] addObject: foo];
There are options that you can consider, for example. you can make a method a class method. You can also make a thread of a method thread safe in a multi-threaded environment. eg.
-(NSMutableArray*) myStaticArray { static NSMutableArray* theArray = nil; @synchronized([ClassA class]) { if (theArray == nil) { theArray = [[NSMutableArray alloc] init]; } } return theArray; }
Jeremyp
source share