我在处理缓存中某些类的持久性时遇到问题。这是我尝试的代码,它根本无法恢复存档数据或删除它:
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)")
答案 0 :(得分:0)
感谢提示的大量流体,代码很好,除了用path替换absoluteString。一旦更换了这部分,一切都无缝地工作。