Robert Constantinescu Robert Constantinescu - 1 year ago 169
Swift Question

iOS Swift - Singleton data persistance

I am developping an application that saves informations about the logged-in user in CoreData and singleton class. After the user log-in, I'm fetching data from coredata and set the variables from the singleton.

My question:

If the app receives memory warning issue, and the data from the singleton will be released, my app will crash. What can I do in this situation?


Answer Source

Let's say you have a local property named NSArray *myArray in singleton's .m file where you store all the needed data. All you need to do is to add a method in header file which returns that array if is not nil, and in case of nil make it reload from storage and return. Also override - (void)didReceiveMemoryWarning method and save the data in case of memory warning.
Here is a sample code written in objective-c:

//Singleton.h file
- (NSArray *)storedData;

//Singleton.m file
@property NSArray *myArray;
- (NSArray *)storedData
    if (_myArray == nil)
        _myArray = [self fetchMyArrayFromLocalStorage];

    return _myArray;

- (NSArray *)fetchMyArrayFromLocalStorage
    //Some code to fetch data from local storage

- (void)saveMyArrayToLocalStorage
    //Code to save _myArray to local storage

- (void)didReceiveMemoryWarning
    [self saveMyArrayToLocalStorage];
    _myArray = nil; //Remove array if is needed
    [super didReceiveMemoryWarning];

Now you'll always get the data you needed simply by calling method:
[[mySingleton sharedInstance] storedData]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download