好吧,当然有可能,这没问题。在我的代码中,我使用了多个对象,它们需要是数据持久的。为此,我使用了对象编码并将它们存储在数据文件中。如:
-(NSString *)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFilename];
}
然后在另一段代码中进一步:
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
NSLog(@"Test 4");
[archiver encodeObject:playerTwo forKey:@"PlayerTwoObject"];
[archiver encodeObject:singlePlayer forKey:@"SinglePlayer"];
[archiver encodeObject:playerOne forKey:@"PlayerOneObject"];
[archiver encodeObject:settings forKey:@"Settings"];
[archiver finishEncoding];
[data writeToFile:[self dataFilePath] atomically:YES];
[singlePlayer release];
[playerOne release];
[playerTwo release];
[settings release];
这可以保存对象。我知道它有效,因为我可以使用以下代码将它们取出:
unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:[[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]]];
SettingsObject *settings = [unarchiver decodeObjectForKey:@"Settings"];
Player *test = [unarchiver decodeObjectForKey:@"PlayerOneObject"];
NSLog(@"Power On Settings Test: %d,%d", [settings playerOneStartingLife], [settings singlePlayerStartingLife]);
NSLog(@"Power On Player Test: %@,%d", [test name], [test life]);
凉爽的!所以现在我可以存储我的对象,并将它们读出。 所以这就是问题所在。 在另一个班级中,我取出我正在存储的一个对象并使用它。不是全部,我只念了一个。然后我在更改设置后再次保存它。但我只保存它:
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:singlePlayer forKey:@"SinglePlayer"];
[archiver finishEncoding];
[data writeToFile:[self dataFilePath] atomically:YES];
[singlePlayer release];
完成此操作后,我存储的所有其余对象都将被删除。现在我很困惑,因为我以为我只是在编辑一键“SinglePlayer”,但显然这会以某种方式删除其余部分?这应该会发生吗?我在发布存档程序时遇到了一些问题,这会不会影响它……我认为不会。有没有人对此有所了解,因为如果我只想编辑其中一个对象,我不想取出所有对象并重新编码它们......
谢谢你的帮助!