使用单例并将其存档

发布于 2024-10-17 13:35:22 字数 2373 浏览 6 评论 0原文

我有一堂课,我想在我的应用程序中保留持久设置。此类定义为:

@interface Archive : NSCoder <NSCoding> {
    NSString *fromAddress;
    NSString *toAddress;
... more ...
}

@property(nonatomic,retain) NSString *fromAddress;
@property(nonatomic,retain) NSString *toAddress;

+ (Archive *)sharedArchive;

-(void)encodeWithCoder:(NSCoder *)aCoder;
-(id)initWithCoder:(NSCoder *)aDecoder;

并实现为:

@synthesize fromAddress, toAddress;

+ (Archive *)sharedArchive
{
    if (sharedArchive == nil) {
        NSMutableData *data = [[NSMutableData alloc] initWithContentsOfFile:@"mydata"];
        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        sharedArchive = [unarchiver decodeObjectForKey:@"myapp"];
        [unarchiver finishDecoding];
    }
    return sharedArchive;
}

+ (id)allocWithZone:(NSZone *)zone
{
    sharedArchive = [super allocWithZone:NULL];
    return sharedArchive;
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)retain
{
    return self;
}

- (NSUInteger)retainCount
{
    return NSUIntegerMax; 
}

- (void)release
{
    //do nothing
}

- (id)autorelease
{
    return self;
}

-(void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.fromAddress forKey:@"fromAddress"];
    [aCoder encodeObject:self.toAddress forKey:@"toAddress"];
}

-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [self initWithCoder:aDecoder];
    fromAddress = [[aDecoder decodeObjectForKey:@"fromAddress"] retain];
    toAddress = [[aDecoder decodeObjectForKey:@"toAddress"] retain];
    return self;
}

应用程序委托 applicationWillTerminate 方法:

- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:[Archive sharedArchive] forKey:@"myapp"];
    [archiver finishEncoding];
    [data writeToFile:@"myapp" atomically:YES];
}

我对归档/取消归档这个概念很陌生。问题是我无法从数据文件中读回。我收到以下错误:

-[NSKeyedUnarchiver initForReadingWithData:]: data is NULL

谁能解释我做错了什么?或者也许是保存/恢复持久数据的更好方法。我已经研究过 NSUserDefaults 类,但我认为这不适合我的情况......我并不是想保存用户首选项。

I have a class where I want to keep persistent settings throughout my app. This class is defined as:

@interface Archive : NSCoder <NSCoding> {
    NSString *fromAddress;
    NSString *toAddress;
... more ...
}

@property(nonatomic,retain) NSString *fromAddress;
@property(nonatomic,retain) NSString *toAddress;

+ (Archive *)sharedArchive;

-(void)encodeWithCoder:(NSCoder *)aCoder;
-(id)initWithCoder:(NSCoder *)aDecoder;

And implemented as:

@synthesize fromAddress, toAddress;

+ (Archive *)sharedArchive
{
    if (sharedArchive == nil) {
        NSMutableData *data = [[NSMutableData alloc] initWithContentsOfFile:@"mydata"];
        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        sharedArchive = [unarchiver decodeObjectForKey:@"myapp"];
        [unarchiver finishDecoding];
    }
    return sharedArchive;
}

+ (id)allocWithZone:(NSZone *)zone
{
    sharedArchive = [super allocWithZone:NULL];
    return sharedArchive;
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)retain
{
    return self;
}

- (NSUInteger)retainCount
{
    return NSUIntegerMax; 
}

- (void)release
{
    //do nothing
}

- (id)autorelease
{
    return self;
}

-(void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.fromAddress forKey:@"fromAddress"];
    [aCoder encodeObject:self.toAddress forKey:@"toAddress"];
}

-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [self initWithCoder:aDecoder];
    fromAddress = [[aDecoder decodeObjectForKey:@"fromAddress"] retain];
    toAddress = [[aDecoder decodeObjectForKey:@"toAddress"] retain];
    return self;
}

The application delegate applicationWillTerminate method:

- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:[Archive sharedArchive] forKey:@"myapp"];
    [archiver finishEncoding];
    [data writeToFile:@"myapp" atomically:YES];
}

I am new on this concept of archive/unarchive. The problem is that I am not being able to read back from the data file. I get the following error:

-[NSKeyedUnarchiver initForReadingWithData:]: data is NULL

Could anyone explain what I am doing wrong? Or perhaps a better way to save/restore persistent data. I've looked into the NSUserDefaults class, but I don't think that fits in my case... I am not trying to save user preferences.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅语花开 2024-10-24 13:35:22

您只想保存那两个字符串吗?使用 NSUserDefaults。

如果您不想使用 NSUserDefaults,您应该提供真实路径而不是 @"myapp" 来 writeToFile 和 readFromFile。

NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [libraryPath stringByAppendingPathComponent:@"myApp"];
[data writeToFile:path atomically:YES];

并且您还应该释放 NSMutableData *dataNSKeyedUnarchiver *unarchiver

顺便说一句,[writeToFile:atomically:] 返回一个 BOOL 告诉您是否写入成功了。

btw2,- (void)applicationWillTerminate:(UIApplication *)application 在启用多任务处理的 iOS4 上不会经常被调用。您也应该将保存函数放入 applicationDidEnterBackground: 中。

You only want to save those two strings? Use NSUserDefaults.

if you don't want to use NSUserDefaults you should provide real paths instead of @"myapp" to writeToFile and readFromFile.

NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [libraryPath stringByAppendingPathComponent:@"myApp"];
[data writeToFile:path atomically:YES];

and you should also release NSMutableData *data and NSKeyedUnarchiver *unarchiver

btw, [writeToFile:atomically:] returns a BOOL that tells you if the write was successful.

btw2, - (void)applicationWillTerminate:(UIApplication *)application won't get called often on iOS4 with enabled multitasking. You should put your save function into applicationDidEnterBackground: too.

酒几许 2024-10-24 13:35:22

@fluchtpunkt 说得对; “你只想保存这两个字符串?使用 NSUserDefaults。”

或者,更具体地说,如果:

有一个我想保留的课程
我的应用程序中的持久设置。

除非您需要保留大量数据(大型 BLOB 等),否则您应该使用 NSUserDefaults。

依赖应用程序终止/应用程序启动时的归档和取消归档充满了潜在问题。应用程序并不总是会被干净地终止,并且在启动时取消归档“整个应用程序”使用的一堆内容(即用于应用程序启动)只会使您的应用程序启动时间变慢。

如果您确实需要在启动之间保留大量状态,那么归档/取消归档当然可以工作。但是,您不应该将归档与终止耦合起来;您是否真的希望用户在应用程序强制退出、抛弃或设备硬重启时丢失数据(许多用户对此有一种不自然的癖好)?

@fluchtpunkt got it right; "You only want to save those two strings? Use NSUserDefaults."

Or, more specifically, if:

have a class where I want to keep
persistent settings throughout my app.

Unless you need to persist some significant quantity of data -- large BLOBs or the like -- you should use NSUserDefaults.

Relying on archiving and unarchiving at app termination / app launch is rife with potential issues. Apps don't always get terminated cleanly and unarchiving a bunch of stuff on launch that is used "throughout the app" (i.e. not used for app startup) is just going to make your app launch times slower.

If you do have some large amount of state that needs to be persisted between launches, then archiving / unarchiving can certainly work. However, you should not couple the archival to termination; do you really want the user to lose data when the app is force quit, jettisoned, or the device is hard rebooted (which many users have an unnatural fetish for doing)?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文