2011-06-09 82 views
0

基本上,我正在制作一个应用程序,将数据保存到自定义文件类型中。我已经设置了将字典存档并将其保存到文件中。然后加载文件,解开字典,并将其放在应该存放的位置。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; 
} 

另一个字符串现在设置在别处,但我需要把它们放在这里。然后,我用“卡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

如果这是你确切的代码,那么它看起来像问题是,你试图解除存档值,你没有存档开始与键(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 
+0

我固定的这些问题,但它仍然不会一切工作。还有其他建议吗? – Justin 2011-06-11 02:46:05

+0

已经有几天了,我还没有听到任何回应。我是否假设你找不到可能导致此问题的其他问题?顺便说一下,我已经更新了代码。 – Justin 2011-06-15 21:55:42

+0

'loadLife:move:'中的'lifeString'和'moveString'是什么?您不能在类方法中访问实例变量。涉及'NSTextFieldCell'的错误消息和这个类'CardBuilder'之间的连接完全不清楚。文本字段单元格在哪里? 'readFromData:...'中的'NSLog'的结果是什么? – 2011-06-16 07:37:12