【问题标题】:Objective C - Singleton not persisting data after App restart [duplicate]目标C - 应用程序重启后单例不保留数据[重复]
【发布时间】:2015-10-28 20:29:08
【问题描述】:

我做一个这样的单例:

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

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

    return sharedInstance;
}

它有一个属性叫做:

@property (nonatomic, strong) NSData *profilePicData;

我保存这样一张图片:

[[CurrentUser sharedInstance] setProfilePicData:profilePictureData];

我像这样加载图像:

if ([[CurrentUser sharedInstance]profilePicData]) {

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

图像显示并且一切正常,但是当我重新启动应用程序并转到包含相同代码的相同视图控制器时,图像不再出现在 UIImageView 中。这让我相信单例不会持续存在。

如何使用单例对象在应用重新启动时保留数据?

【问题讨论】:

    标签: ios objective-c singleton


    【解决方案1】:

    单例实例仅在应用程序运行时处于活动状态。您需要在设置时将profilePictureData 保存到文件中,然后在创建单例时加载它,一旦应用再次运行。

    对于写作,您可以使用[profilePicData writeToURL:atomically:]

    然后在你的单例初始化程序中,你应该使用[NSData dataWithContentsOfURL:]再次将此文件加载到profilePicData

    用于写入的 URL 必须与用于加载的 URL 相同,并且必须位于应用的沙箱内。

    NSData's documentation.

    【讨论】:

      猜你喜欢
      • 2010-12-24
      • 1970-01-01
      • 2010-12-18
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 2016-09-06
      • 2010-11-19
      • 1970-01-01
      相关资源
      最近更新 更多