我无法让添加到收藏夹功能正常工作。这是我用来为收藏夹数据设置数组和字典的代码:
在应用程序委托中,在“appDidFinishLaunching”中:
delegateFavouritesDictionary = [NSMutableDictionary dictionary];
NSLog(@"Mutable Dictionary: %@", delegateFavouritesDictionary);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Saved.data"];
[delegateFavouritesDictionary writeToFile:filePath atomically: YES];
delegateFavouritesArray = [[NSMutableArray alloc] init];
然后在我的 detailViewController 中,我有一个 addToFavourites 函数:
if([[addToFavouritesDictionary allKeys] containsObject:ID]) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Saved.data"];
[addToFavouritesDictionary removeObjectForKey:ID];
[addToFavouritesArray removeObject:Name];
[favouritesButton setTitle:@"+ Favourites" forState:(UIControlState)UIControlStateNormal];
[addToFavouritesDictionary writeToFile:filePath atomically: YES];
NSLog(@"New Dictionary: %@", addToFavouritesDictionary);
} else {
[addToFavouritesArray addObject:Name];
NSString *ID = [[NSUserDefaults standardUserDefaults]objectForKey:@"ID"];
[addToFavouritesDictionary setObject:Name forKey:ID];
[favouritesButton setTitle:@"- Favourites" forState:(UIControlState)UIControlStateNormal];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Saved.data"];
[addToFavouritesDictionary writeToFile:filePath atomically: YES];
NSLog(@"Mutable Dictionary: %@", addToFavouritesDictionary);
//[addToFavouritesDictionary release];
}
上面的代码按预期工作,在应用程序启动时,它设置一个字典并将“Saved.data”的内容加载到字典中,然后在 detailViewController 中,它加载“Saved.data”文件并添加或删除该文件. 我遇到的问题是当 iPhone 重新启动时,所有收藏夹数据都消失了,或者如果应用程序崩溃然后再次打开,收藏夹中的所有数据都消失了。有什么方法可以在每次设备重启或关机时保存数据而不被删除?
提前谢谢了。