How to create Static NSMutableArray in class in Objective c?

I have a class A, which is a superclass for class B and class C. I need to save the objects of class A to "static" NSMutablearray defined in class A. Is it possible to change the data stored in MSMutableArray using methods in Class B and class C? How to create and initialize a static array? An example would be additional help. thanks in advance.

+7
arrays objective-c static-members
source share
1 answer

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; } 
+14
source share

All Articles