swift:博客+多个实体的带滑出式导航的核心数据
swift: core data with slideout navigation for a blog + multiple entities
我正在制作一个博客 reader 应用程序,其中博客的类别列在滑出导航中,每个类别获取唯一的 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!
是抓取的类别url
因此,每次我 select 从滑出式导航中创建一个新类别时,核心数据都会被新类别的内容覆盖,并且加载时间过长。
关于我的问题,是否可以在核心数据中为每个类别设置一个唯一的实体,这样结果就不会被覆盖??实施这样的事情是否可取?
我无法理解如果我获取它们各自实体中的所有类别,我将如何在 CenterViewController 的同一个 UITableview 中显示它们?
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!
}
我已经无计可施了..求求你帮忙
是的,这是可能的,也是可取的。在类别实体和 MIBlog 实体之间创建关系。将每个 MIBlog 对象保存到 Core Data 时,您应该检查 name/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]
}
我正在制作一个博客 reader 应用程序,其中博客的类别列在滑出导航中,每个类别获取唯一的 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!
是抓取的类别url
因此,每次我 select 从滑出式导航中创建一个新类别时,核心数据都会被新类别的内容覆盖,并且加载时间过长。
关于我的问题,是否可以在核心数据中为每个类别设置一个唯一的实体,这样结果就不会被覆盖??实施这样的事情是否可取?
我无法理解如果我获取它们各自实体中的所有类别,我将如何在 CenterViewController 的同一个 UITableview 中显示它们?
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!
}
我已经无计可施了..求求你帮忙
是的,这是可能的,也是可取的。在类别实体和 MIBlog 实体之间创建关系。将每个 MIBlog 对象保存到 Core Data 时,您应该检查 name/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]
}