Search code examples
iphoneobjective-cnsmutablearrayuiapplicationiphone-developer-program

Can i have a single NSMutableArray in my multiple views application?


I have a navigational based application which has multiple views. Is it possible to use one single NSMutableArray for the whole applicaiton? Can i add objects to that NSMutableArray in one view and then remove object from the same NSMutableArray from some other view? I tried

 myappAppDelegate *appDelegate = (myappAppDelegate *)[[UIApplication sharedApplication] delegate];

but it gives me null when i try to access appDelegate's array. If anyone can give me any idea or helping link or tutrorial. Thanks in advance.


Solution

  • If you are having multiple views in your application, and in that case you want to have a variable accessible to every view, you should always create a Model/Data(singleton) class and define the variable in it. Something like this :

    //DataClass.h      
    
    @interface DataClass : NSObject {    
    
    NSMutableArray *arrGlobal;     
    
    }    
    @property(nonatomic,retain)NSMutableArray *arrGlobal;   
    +(DataClass*)getInstance;    
    @end  
    
    
    
    //DataClass.m    
    @implementation DataClass    
    @synthesize arrGlobal;    
    static DataClass *instance =nil;    
    +(DataClass *)getInstance    
    {    
        @synchronized(self)    
        {    
            if(instance==nil)    
            {    
    
                instance= [DataClass new];    
            }    
        }    
        return instance;    
    }    
    

    Now in your view controller you need to call this method as :

    DataClass *obj=[DataClass getInstance];  
    obj.arrGlobal = arrLocal; 
    

    This variable will be accessible to every view controller. You just have to create an instance of Data class.