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.
A:
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;
}
JeremyP
2010-10-06 13:00:42