什么时候应该清除Core Data缓存实体?

时间:2015-06-10 12:46:06

标签: swift caching core-data

我在http://www.raywenderlich.com/76735/using-nsurlprotocol-swift

的教程中使用代码

在该教程中,代码缓存每个请求。

我的问题是何时以及如何清除缓存实体(核心数据)?或者我们不需要清除缓存实体?

缓存实体是我保存NSConnection请求的所有数据的实体。如果我们需要清除核心数据中的缓存,我如何选择要保留的数据和其他要删除的数据。

例如,我正在制作新闻应用。每个VC都有标题,如标题,日期,类别和UIWebView。当应用程序关闭时,我想删除除“已保存的新闻”之外的所有缓存链接。 “已保存的新闻”是用户通过点击“加号”按钮选择的类别。

我正在考虑创建一个名为“isToSave”的新列。因此,当用户点击按钮进行保存时。我需要解析内容文本并提取链接(src =)并在CoreData中将列“isToSave”设置为true。当app关闭时,我将删除列为“isTosave”= false

的所有链接

很快:清除实体“cacheURls”是不错的做法,如果是,我如何通过选择清除网址?

这是代码:

import UIKit
import CoreData

var requestCount = 0


class MyURLProtocol: NSURLProtocol {

    var connection: NSURLConnection!
    var mutableData: NSMutableData!
    var response: NSURLResponse!

    override class func canInitWithRequest(request: NSURLRequest) -> Bool {
        println("Request #\(requestCount++): URL = \(request.URL.absoluteString)")

        if NSURLProtocol.propertyForKey("MyURLProtocolHandledKey", inRequest: request) != nil {
            return false
        }

        return true
    }

    override class func canonicalRequestForRequest(request: NSURLRequest) -> NSURLRequest {
        return request
    }

    override class func requestIsCacheEquivalent(aRequest: NSURLRequest,
        toRequest bRequest: NSURLRequest) -> Bool {
            return super.requestIsCacheEquivalent(aRequest, toRequest:bRequest)
    }

    override func startLoading() {


        // 1
        let possibleCachedResponse = self.cachedResponseForCurrentRequest()
        if let cachedResponse = possibleCachedResponse {
            println("Serving response from cache")

            // 2
            let data = cachedResponse.valueForKey("data") as NSData!
            let mimeType = cachedResponse.valueForKey("mimeType") as String!
            let encoding = cachedResponse.valueForKey("encoding") as String!

            // 3
            let response = NSURLResponse(URL: self.request.URL, MIMEType: mimeType, expectedContentLength: data.length, textEncodingName: encoding)

            // 4
            self.client!.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: .NotAllowed)
            self.client!.URLProtocol(self, didLoadData: data)
            self.client!.URLProtocolDidFinishLoading(self)
        } else {
            // 5
            println("Serving response from NSURLConnection")

            var newRequest = self.request.mutableCopy() as NSMutableURLRequest
            NSURLProtocol.setProperty(true, forKey: "MyURLProtocolHandledKey", inRequest: newRequest)
            self.connection = NSURLConnection(request: newRequest, delegate: self)
        }


    }

    override func stopLoading() {
        if self.connection != nil {
            self.connection.cancel()
        }
        self.connection = nil
    }

    func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
        self.client!.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: .NotAllowed)
        self.response = response
        self.mutableData = NSMutableData()
    }

    func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
        self.client!.URLProtocol(self, didLoadData: data)
        self.mutableData.appendData(data)
    }

    func connectionDidFinishLoading(connection: NSURLConnection!) {
        self.client!.URLProtocolDidFinishLoading(self)
        self.saveCachedResponse()
    }

    func connection(connection: NSURLConnection!, didFailWithError error: NSError!) {
        self.client!.URLProtocol(self, didFailWithError: error)
    }


    func saveCachedResponse () {
        println("Saving cached response")

        // 1
        let delegate = UIApplication.sharedApplication().delegate as AppDelegate
        let context = delegate.managedObjectContext!

        // 2
        let cachedResponse = NSEntityDescription.insertNewObjectForEntityForName("CachedURLResponse", inManagedObjectContext: context) as NSManagedObject

        cachedResponse.setValue(self.mutableData, forKey: "data")
        cachedResponse.setValue(self.request.URL.absoluteString, forKey: "url")
        cachedResponse.setValue(NSDate(), forKey: "timestamp")
        cachedResponse.setValue(self.response.MIMEType, forKey: "mimeType")
        cachedResponse.setValue(self.response.textEncodingName, forKey: "encoding")

        // 3
        var error: NSError?
        let success = context.save(&error)
        if !success {
            println("Could not cache the response")
        }
    }

    func cachedResponseForCurrentRequest() -> NSManagedObject? {
        // 1
        let delegate = UIApplication.sharedApplication().delegate as AppDelegate
        let context = delegate.managedObjectContext!

        // 2
        let fetchRequest = NSFetchRequest()
        let entity = NSEntityDescription.entityForName("CachedURLResponse", inManagedObjectContext: context)
        fetchRequest.entity = entity

        // 3
        let predicate = NSPredicate(format:"url == %@", self.request.URL.absoluteString!)
        fetchRequest.predicate = predicate

        // 4
        var error: NSError?
        let possibleResult = context.executeFetchRequest(fetchRequest, error: &error) as Array<NSManagedObject>?

        // 5
        if let result = possibleResult {
            if !result.isEmpty {
                return result[0]
            }
        }

        return nil
    }

}

0 个答案:

没有答案