我在处理缓存中某些类的持久性时遇到问题。这是我尝试过的代码,它在恢复存档数据或删除它时根本不起作用:
func cacheDirectoryURL()->NSURL?{
let fileManager=NSFileManager()
let urls = fileManager.URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask)
if urls.count>0{
return urls[0]
}
return nil
}
func palineCacheURL()->NSURL?{
let url=cacheDirectoryURL()?.URLByAppendingPathExtension("Paline.archive")
return url
}
public func getMapHandlerWithDelegate(delegate:MovableAnnotationDelegate)->MapDelegate{
let archiveURL=palineCacheURL()!
mapHandler=NSKeyedUnarchiver.unarchiveObjectWithFile(archiveURL.absoluteString) as? MapDelegate
if mapHandler != nil{
mapHandler!.delegate=delegate;
} else {
mapHandler=MapDelegate.sharedMapDelegate()
mapHandler!.delegate=delegate;
}
return mapHandler!
}
func clearMapArchives(){
do{
try NSFileManager.defaultManager().removeItemAtPath(palineCacheURL()!.absoluteString);
} catch let error as NSError {
print(error.localizedDescription+" "+(error.localizedFailureReason ?? ""));
let alert=UIAlertView(title:NSLocalizedString("Error", comment:""), message:NSLocalizedString("Unable to clean the cache; please reinstall the app in the case of problems", comment:""), cancelButtonTitle:NSLocalizedString("Dismiss", comment:""), otherButtonTitle:nil, onDismiss:nil, onCancel:nil)
alert.show()
}
}
func archive(){
//-NSLog(@"archivePath=%@ paline=%@", archivePath, self.palineArray);
if mapHandler != nil {
NSKeyedArchiver.archiveRootObject(mapHandler!, toFile: palineCacheURL()!.absoluteString)
print("archivio a \(palineCacheURL()!.absoluteString)")
}
}
我什至尝试在保存对象后立即检索它,结果为零:
NSKeyedArchiver.archiveRootObject(mapHandler!, toFile: palineCacheURL().absoluteString)
print("archivio a \(palineCacheURL().absoluteString)")
let restored=NSKeyedUnarchiver.unarchiveObjectWithFile(palineCacheURL().absoluteString) as? MapDelegate
print("restored \(restored)")