【发布时间】:2014-06-22 16:08:20
【问题描述】:
我目前正在尝试向我的应用添加游戏保存功能。最终目标是将约 300 个自定义对象保存到 .plist 文件中,稍后再提取它们。我已经取得了一些进展,但我遇到了initWithCoder: 的一些问题,而且我也不确定我的技术。
UIViewController 正在使用以下代码来保存对象(我只在字典中添加了 2 个对象作为示例):
//Saves the contents to a file using an NSMutableDictionary
-(IBAction)saveContents {
//Create the dictionary
NSMutableDictionary *dataToSave = [NSMutableDictionary new];
//Add objects to the dictionary
[dataToSave setObject:label.text forKey:@"label.text"];
[dataToSave setObject:territory forKey:@"territory"];
[dataToSave setObject:territory2 forKey:@"territory2"];
//Archive the dictionary and its contents and set a BOOL to indicate if it succeeds
BOOL success = [NSKeyedArchiver archiveRootObject:dataToSave toFile:[self gameSaveFilePath]];
//Handle success/failure here...
//Remove and free the dictionary
[dataToSave removeAllObjects]; dataToSave = nil;
}
这成功调用了Territory类中的encodeWithCoder:函数两次:
-(void)encodeWithCoder:(NSCoder *)aCoder {
NSLog(@"ENCODING");
[aCoder encodeObject:self.data forKey:@"data"];
[aCoder encodeInt:self.MMHValue forKey:@"MMHValue"];
[aCoder encodeObject:self.territoryName forKey:@"territoryName"];
//Continue with other objects
}
当我查看目录时,果然文件存在。 现在,这是我遇到的问题: 运行以下函数时,initWithCoder: 函数被成功调用了两次。 initWithCoder: 函数中的日志内部输出它们应该输出的内容,但UIViewController 的loadContents 函数中的日志返回0、null 等。但是,标签的文本设置正确。
//Loads the contents from a file using an NSDictionary
-(IBAction)loadContents {
//Create a dictionary to load saved data into then load the saved data into the dictionary
NSDictionary *savedData = [NSKeyedUnarchiver unarchiveObjectWithFile:[self gameSaveFilePath]];
//Load objects using the dictionary's data
label.text = [savedData objectForKey:@"label.text"];
NSLog(@"%i, %i", [territory intAtKey:@"Key4"], [territory2 intAtKey:@"Key4"]);
NSLog(@"MMH: %i, %i", territory.MMHValue, territory2.MMHValue);
NSLog(@"NAME: %@, %@", territory.territoryName, territory2.territoryName);
//Free the dictionary
savedData = nil;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
NSLog(@"DECODING TERRITORY");
self.data = [aDecoder decodeObjectForKey:@"data"];
self.MMHValue = [aDecoder decodeIntForKey:@"MMHValue"];
self.territoryName = [[aDecoder decodeObjectForKey:@"territoryName"] copy];
//Continue with other objects
}
NSLog(@"DECODED INT: %i", self.MMHValue);
NSLog(@"DECODED NAME: %@", self.territoryName);
return self;
}
我一直试图让它工作几个小时,但无济于事。如果有人对此有任何见解,请帮助我。另外,我不完全确定我的保存技术是否良好(使用NSMutableDictionary 来存储对对象的引用,以便它可以输出到一个文件)?谢谢!
【问题讨论】:
-
您是用
plist还是NSCoding保存它?它们完全不同。 -
我正在保存到一个 plist 文件。
-
我不认为
NSKeyedArchiver可以创建plist文件。 -
他们绝对可以,
[NSKeyedArchiver archiveRootObject:dataToSave toFile:[self gameSaveFilePath]];就是这样做的,哈哈
标签: ios objective-c initwithcoder nskeyedunarchiver