【问题标题】:Archiving, unarchiving and cleaning objects in cache with Swift使用 Swift 归档、取消归档和清理缓存中的对象
【发布时间】:2016-03-03 07:33:42
【问题描述】:

我在处理缓存中某些类的持久性时遇到了问题。这是我尝试过的代码,无论是恢复存档数据还是删除它都不起作用:

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)")

【问题讨论】:

  • 定义“不起作用”
  • 与您的实际问题无关,我强烈建议您在使用 Swift 时不要使用NSKeyed(Un)Archiver。在更改类结构/类名/模块名甚至访问说明符(私有/内部/公共)时会引起很多麻烦。特别是。存档器将类名存储为字符串,Swift 中的类名往往非常神秘——比如__TFCCC4test1a1b1c1dfS2_FTS0_1xS1_1vFT1xSi_Si_OVS_1e1f(不是实际的类,只是一个示例)。向后兼容真的很烦人。
  • 不管怎样,你有解决办法吗?
  • 那么如何将归档对象保存在缓存中?
  • iOS 上有 Core Data、sqlite、Realm 和其他各种用于持久存储的库。 -- 对于存档,您应该检查init(coder:) 是否实际上在您的MapDelegate 上被调用并且不返回nil。此外,您的 MapDelegate 必须符合 NSCoding 并正确实施 encodeWithCoder(_:)。 - 就像@SergioTulentsev 所说,您应该准确解释它在哪里停止按预期工作。使用调试器逐步运行您的代码。

标签: swift nsfilemanager nskeyedarchiver nskeyedunarchiver


【解决方案1】:

非常感谢fluidsonic 的提示,除了absoluteString 被path 替换之外,代码很好。更换此部件后,一切都可以无缝运行。

【讨论】:

    猜你喜欢
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    相关资源
    最近更新 更多