1

I am trying to develop a iOS app that has different scene but all of them are sharing a single data source which is a NSMutableArray (dataArray). Is it possible to modify ie add / delete items to that array from all of those different scenes.

Note:

I know how to modify/add/delete that array from a single scene (ViewController UI).

  • 1
    If you pass the same reference to the `NSMutableArray` then yes, each one can modify the same array. – rmaddy Jun 18 '15 at 23:45
  • do i need to declare that array as global array? – tiny_iOS_developer Jun 18 '15 at 23:48
  • If you "pass the same reference" then it does not need to be global. You say they **are sharing** the array...how is that happening now? – Phillip Mills Jun 18 '15 at 23:55
  • 1
    Sounds like you need to create a shared singleton (model) that you can use in each of your classes. Just do search and you will find plenty of examples. See here: http://stackoverflow.com/questions/145154/what-should-my-objective-c-singleton-look-like – rmp Jun 18 '15 at 23:57

1 Answers1

0

Simply Create a singleton class similar to this... i.e if you are using ARC.

MyGlobalData.h

@interface MyGlobalData : NSObject 
{
   NSMutableArray *myData;
}

@property (nonatomic, retain) NSMutableArray *myData;
+ (id)sharedManager;
@end

MyGlobalData.m

@implementation MyGlobalData
@synthesize myData;

+ (id)sharedManager 
{
    static MyGlobalData *sharedData = nil;
    @synchronized(self) 
    {
       if (sharedData == nil)
        sharedData = [[self alloc] init];
    }
    return sharedData;
 }

 - (id)init 
 {
    if (self = [super init]) 
    {
       myData = [[NSMutableArray alloc] init];
    }
    return self;
 }

 - (void)dealloc {}

@end

Your Scene A Controller

-someMethod()
{
   MyGlobalData *sharedObject = [MyGlobalData sharedManager];
}

Your Scene N Controller

-someMethod()
{
   MyGlobalData *sharedManager = [MyGlobalData sharedManager];
}

Note: You can also use GCD in sharedManager but I'll leave it to you. Figure it out. Also this implementation will be bit different if you are not using ARC in your project.

Srinivasan N
  • 611
  • 9
  • 20