Objective C - 应用重启后单例不持久化数据
Objective C - Singleton not persisting data after App restart
我做的单例是这样的:
+ (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
中。这让我相信单例不会持久化。
如何使用单例对象在应用程序重新启动时保留数据?
单例实例仅在应用 运行ning 时有效。您需要在设置时将 profilePictureData
保存到文件中,然后在创建单例时加载它,一旦应用程序再次 运行。
对于写作你可以使用[profilePicData writeToURL:atomically:]
然后在您的单例初始化程序中,您应该使用 [NSData dataWithContentsOfURL:]
再次将此文件加载到 profilePicData
用于写入的 URL 必须与您用于加载的相同,并且必须在您应用的沙箱中。
我做的单例是这样的:
+ (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
中。这让我相信单例不会持久化。
如何使用单例对象在应用程序重新启动时保留数据?
单例实例仅在应用 运行ning 时有效。您需要在设置时将 profilePictureData
保存到文件中,然后在创建单例时加载它,一旦应用程序再次 运行。
对于写作你可以使用[profilePicData writeToURL:atomically:]
然后在您的单例初始化程序中,您应该使用 [NSData dataWithContentsOfURL:]
profilePicData
用于写入的 URL 必须与您用于加载的相同,并且必须在您应用的沙箱中。