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

前端 未结 4 1166
小鲜肉
小鲜肉 2020-12-22 09:05

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 NSMuta

相关标签:
4条回答
  • 2020-12-22 09:13

    On the Singleton approach add this

    instance.arrGlobal = [[NSMutableArray alloc] init];
    

    this way:

    @synchronized(self)    
    {    
        if(instance==nil)    
        {    
    
            instance= [DataClass new];
            instance.arrGlobal = [[NSMutableArray alloc] init];
        }    
    }    
    return instance;
    

    This way you can initilize the array and use it properly.

    0 讨论(0)
  • 2020-12-22 09:14

    For your type of issue I would use a singleton.

    http://en.wikipedia.org/wiki/Singleton_pattern

    The appdelegate is a singleton too but you can reduce a bit the number of coded lines if you use your own singleton.

    0 讨论(0)
  • 2020-12-22 09:34

    The AppDelegate approach should work, and you should probably figure out why it's not working, even if you go with a singleton.

    The statement to get your appDelegate pointer appears to be correct, so I'm guessing that the pointer to the array is either not getting set (and retained) in your myappDelegate class, or you did not create the AppDelegate instance correctly in the first place.

    0 讨论(0)
  • 2020-12-22 09:36

    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.

    0 讨论(0)
提交回复
热议问题