0

I make a singleton like this:

+ (CurrentUser *)sharedInstance {
    static id sharedInstance = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });

    return sharedInstance;
}

It has a property called:

@property (nonatomic, strong) NSData *profilePicData;

I save an image like this:

[[CurrentUser sharedInstance] setProfilePicData:profilePictureData];

I load the image like this:

if ([[CurrentUser sharedInstance]profilePicData]) {

    self.profileImageView.image = [UIImage imageWithData:[[CurrentUser sharedInstance]profilePicData]];
}

The image shows up and everything is good, but when I restart the app and go to the same view controllers that contain this same code, the image no longer appears in the UIImageView. This leads me to believe the singleton is not persisting.

How do I persist the data across app restarts with a singleton object?

Brandon A
  • 8,153
  • 3
  • 42
  • 77

1 Answers1

3

The singleton instance is only alive while the app is running. You need to save profilePictureData to a file when it is set and then load it when the singleton gets created, once the app is run again.

For writing you can use [profilePicData writeToURL:atomically:]

Then in your singleton's initializer you should load this file into profilePicData again with [NSData dataWithContentsOfURL:]

The URL used for writing must be the same you use for loading, and must be within your app's sandbox.

See NSData's documentation.

pevasquez
  • 862
  • 8
  • 14