swift:具有博客+多个实体的滑出导航的核心数据

时间:2015-02-23 06:27:25

标签: ios json swift core-data entity

我正在创建一个博客阅读器应用程序,其中博客的类别列在幻灯片导航中,每个类别都会获取独特的JSON结果并显示在CenterViewController中

现在,CenterViewConroller将数据保存到CoreData中,然后使用以下代码在UITableView中显示它:

func animalSelected(animal: Animal) {

var appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var context: NSManagedObjectContext = appDel.managedObjectContext!

showProgressHUD()

let session = NSURLSession.sharedSession()
var error : NSError?
 var posts = [[String:String]()]

let task = session.dataTaskWithURL(animal.url!, completionHandler: {data, response, error -> Void in

    if (error != nil){
        println(error)

    }else{

        var request = NSFetchRequest(entityName: "MIBlog")
        request.returnsObjectsAsFaults = false
        var results = context.executeFetchRequest(request, error: nil)

        for result in results!
        {
            context.deleteObject(result as NSManagedObject)
            context.save(nil)

        }


        let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

        var post:AnyObject

        var authorDictionary:AnyObject
        var newBlogItem:NSManagedObject
        for var i = 0; i < jsonResult["posts"]!.count; i++
        {
            posts.append([String:String]())
            post = jsonResult["posts"]![i] as NSDictionary
            posts[i]["title"] = post["title"] as? NSString
            posts[i]["publishedDate"] = post["date"] as? NSString
            posts[i]["content"] = post["content"] as? NSString
            authorDictionary = post["author"] as NSDictionary
            posts[i]["author"] = post["name"] as? NSString
            posts[i]["thumbnailURL"] = post["thumbnail"] as? NSString
            posts[i]["postURL"] = post["url"] as? NSString


            newBlogItem = NSEntityDescription.insertNewObjectForEntityForName("MIBlog", inManagedObjectContext: context) as NSManagedObject
            newBlogItem.setValue(posts[i]["title"], forKey: "title")
            newBlogItem.setValue(posts[i]["publishedDate"], forKey: "publishedDate")
            newBlogItem.setValue(posts[i]["content"], forKey: "content")
            newBlogItem.setValue(posts[i]["author"], forKey: "author")
            newBlogItem.setValue(posts[i]["thumbnailURL"], forKey: "thumbnailURL")
             newBlogItem.setValue(posts[i]["postURL"], forKey: "postURL")

             context.save(nil)
        }

       request = NSFetchRequest(entityName: "MIBlog")
        request.returnsObjectsAsFaults = false
   results = context.executeFetchRequest(request, error: nil)

    }   
})

task.resume()

delegate?.collapseSidePanels?()

}

注意:在代码中animal.url!是获取类别的网址

因此,每次从幻灯片导航中选择一个新类别时,核心数据都会被新类别的内容覆盖,并且加载时间过长。

提出我的问题,是否有可能在每个类别的coredata中有一个唯一的实体,以便结果不会被覆盖?是否可以实现这样的事情?

我无法确定如果我在各自的实体中获取所有类别,我将如何在我的同一个UITableview中为CenterViewController显示它们?

FetchResultController

// MARK: - Fetched results controller

var fetchedResultsController: NSFetchedResultsController {
    if _fetchedResultsController != nil {
        return _fetchedResultsController!
        }
        var appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        self.managedObjectContext = appDel.managedObjectContext

        let fetchRequest = NSFetchRequest()
        // Edit the entity name as appropriate.
        let entity = NSEntityDescription.entityForName("MIBlog", inManagedObjectContext: self.managedObjectContext!)
        fetchRequest.entity = entity

        // Set the batch size to a suitable number.
        fetchRequest.fetchBatchSize = 20

        // Edit the sort key as appropriate.
        let sortDescriptor = NSSortDescriptor(key: "publishedDate", ascending: false)
        let sortDescriptors = [sortDescriptor]

        fetchRequest.sortDescriptors = [sortDescriptor]

        // Edit the section name key path and cache name if appropriate.
        // nil for section name key path means "no sections".
        let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master")
        aFetchedResultsController.delegate = self
        _fetchedResultsController = aFetchedResultsController

        var error: NSError? = nil
        if !_fetchedResultsController!.performFetch(&error) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            //println("Unresolved error \(error), \(error.userInfo)")
            abort()
        }

        return _fetchedResultsController!
}

在我的智慧结束时..请帮助

1 个答案:

答案 0 :(得分:0)

是的,这是可能的,这是可取的。在Category实体和MIBlog实体之间创建关系。将每个MIBlog对象保存到Core Data时,应检查是否存在该名称/ id的类别,如果存在,则使用它,如果不存在,则创建该类别。我使用这些函数来执行此操作:

func fetchCategory(name: String) -> Category? {

    let fetchRequest = NSFetchRequest(entityName: "Category")
    let predicate = NSPredicate(format: "name = %@", name)

    // Assign fetch request properties
    fetchRequest.predicate = predicate
    fetchRequest.fetchBatchSize = 1
    fetchRequest.fetchLimit = 1

    // Handle results
    let fetchedResults = managedObjectContext?.executeFetchRequest(fetchRequest, error: nil)

    if fetchedResults?.count != 0 {

        if let fetchedCategory: Category = fetchedResults![0] as? Category {
            return fetchedCategory
        }
    }
    return nil
}

func fetchOrCreateCategory(name: String) -> Category {
    if let category = fetchCategory(name) {
        return category
    } else {
        if !name.isEmpty {
            createCategory(name)
            return fetchOrCreateCategory(name)
        } else {
            return fetchOrCreateCategory("Other")
        }
    }
}

然后,您可以使用类别实体的获取请求轻松检索数组中的所有类别,您甚至可以检查以确保该类别实际上包含博客帖子。

func fetchCategories() -> [Category] {
    let fetchRequest = NSFetchRequest(entityName: "Category")
    let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
    let predicate = NSPredicate(format: "blogs.@count != 0") // blogs is whatever you relationship attribute is

    fetchRequest.predicate = predicate
    fetchRequest.sortDescriptors = [sortDescriptor]

    return managedObjectContext?.executeFetchRequest(fetchRequest, error: nil) as! [Category]
}