gpt4 book ai didi

objective-c - NSDictionary 无法正确保存数据

转载 作者:行者123 更新时间:2023-12-03 18:01:12 24 4
gpt4 key购买 nike

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

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

工作中

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] *** -[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] 无效参数不满足:aString != nil

有人可以告诉我为什么这不起作用吗?

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

最佳答案

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

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

关于objective-c - NSDictionary 无法正确保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6298243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com