NSDictionary无法正确保存数据

时间:2011-06-09 19:35:41

标签: objective-c cocoa nsdictionary

基本上,我正在创建一个将数据保存到自定义文件类型的应用程序。我有它设置归档字典并将其保存到文件中。然后它加载文件,取消归档字典,并将它们放在应有的位置。

不幸的是,我无法让我的字典真正保存数据。我有两个例子。

工作

NSDictionary *theDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"test", @"test2", nil];

这将以我想要的方式保存“测试”,我可以完美地加载它。

不工作

NSString *aString = @"test";
NSDictionary *theDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:aString, @"test2", nil];

当我加载文件时,这只给了我一个完全空的字符串。

这是我的确切代码。

- (NSData*)dataOfType:(NSString *)typeName error:(NSError **)outError {
    [fileContents release];

    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

    NSDictionary *theDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:[lifeText stringValue], @"life", [moveText stringValue], @"move", nil];
    [archiver encodeObject:theDictionary forKey:@"SomeKeyValue"];
    [archiver finishEncoding];
    fileContents = [NSData dataWithData:data];
    [archiver release];

    return fileContents;
}

- (BOOL) readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError {
    fileContents = [data retain];

    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    loadedFileDictionary = [[unarchiver decodeObjectForKey:@"SomeKeyValue"] retain];

    [unarchiver finishDecoding];
    [unarchiver release];

    NSLog(@"%@", [loadedFileDictionary valueForKey:@"life"]);

    [Card_Building loadLife:[loadedFileDictionary valueForKey:@"life"] move:[loadedFileDictionary valueForKey:@"move"]];

    return YES;
}

其他字符串暂时设置在别处,但我也需要将它们放在这里。然后,我在“Card Builder.m”中使用以下代码将字符串放在我想要的位置:

+ (void) loadLife:(NSString*)life move:(NSString*)move; {
    lifeString = life;
    moveString = move;
    importData = TRUE;
}

我不明白为什么这不起作用。每次我测试这个,我得到一个空字符串和以下错误消息:

2011-06-09 13:33:56.082 HS-Cards[6479:a0f] *** Assertion failure in -[NSTextFieldCell _objectValue:forString:errorDescription:], /SourceCache/AppKit/AppKit-1038.35/AppKit.subproj/NSCell.m:1531

2011-06-09 13:33:56.082 HS-Cards[6479:a0f] Invalid parameter not satisfying: aString != nil

有人请告诉我为什么这不起作用?

编辑:使用此更新的代码,它加载一次并给我相同的错误消息,但然后它拒绝加载。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果这是您确切的代码,那么问题就是您尝试取消归档您的密钥(moverangeattack等)的值。没有存档开始。您还将lifeValue放入归档字典两次,这是不必要的,因为您两次使用相同的密钥,并且没有实际效果:

NSString *lifeValue = [lifeText stringValue];
NSDictionary *theDictionary = [[NSDictionary alloc] 
                                  initWithObjectsAndKeys:lifeValue, @"life", nil];
                                                       // ^^ Once
[theDictionary setObject:[lifeText stringValue] forKey:@"life"];
                         // ^^ Again; doesn't really do anything
相关问题