我目前正在尝试向我的应用程序添加游戏保存功能。最终目标是将大约 300 个自定义对象保存到一个.plist
文件中,并在以后再次提取它们。我已经取得了一些进展,但我遇到了一些问题,initWithCoder:
而且我也不确定我的技术。
a 正在使用以下代码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;
}
这成功地调用了类encodeWithCoder:
中的函数Territory
两次:
-(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
存储对对象的引用以便输出到一个文件)?谢谢!