coredata stack

This commit is contained in:
Chris Li 2016-11-08 10:14:45 -05:00
parent ee3ee94527
commit a8ef99a8da
15 changed files with 56 additions and 88 deletions

View File

@ -207,69 +207,21 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "self.Kiwix" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "Kiwix", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let libDirPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.libraryDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first!
let libDirURL = URL(fileURLWithPath: libDirPath, isDirectory: true)
let url = libDirURL.appendingPathComponent("kiwix.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this 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.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
return managedObjectContext
}()
// MARK: - Core Data Saving support
lazy var persistentContainer = CoreDataContainer()
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// 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.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
}
let context = persistentContainer.viewContext
if context.hasChanges {
try? context.save()
}
}
// MARK: - Accessor
class var persistentContainer: CoreDataContainer {
return (UIApplication.shared.delegate as! AppDelegate).persistentContainer
}
}

View File

@ -50,7 +50,7 @@ class BookDetailController: UITableViewController, DZNEmptyDataSetSource, DZNEmp
fileprivate(set) var cellTitles = [[String]]()
var bookmarkCount: Int? {
guard let book = book else {return nil}
return Article.fetchBookmarked(in: book, with: NSManagedObjectContext.mainQueueContext).count
return Article.fetchBookmarked(in: book, with: AppDelegate.persistentContainer.viewContext).count
}
override func viewDidLoad() {

View File

@ -306,7 +306,7 @@ class CloudBooksController: UITableViewController, NSFetchedResultsControllerDel
// MARK: - Fetched Results Controller
let managedObjectContext = NSManagedObjectContext.mainQueueContext
let managedObjectContext = AppDelegate.persistentContainer.viewContext
lazy var fetchedResultController: NSFetchedResultsController<Book> = {
let fetchRequest = Book.fetchRequest()
let langDescriptor = NSSortDescriptor(key: "language.name", ascending: true)

View File

@ -240,7 +240,7 @@ class DownloadTasksController: UITableViewController, NSFetchedResultsController
// MARK: - Fetched Results Controller
let managedObjectContext = UIApplication.appDelegate.managedObjectContext
let managedObjectContext = AppDelegate.persistentContainer.viewContext
lazy var fetchedResultController: NSFetchedResultsController<DownloadTask> = {
let fetchRequest = DownloadTask.fetchRequest()
let creationTimeDescriptor = NSSortDescriptor(key: "creationTime", ascending: true)

View File

@ -15,7 +15,7 @@ class LanguageFilterController: UITableViewController, NSFetchedResultsControlle
@IBOutlet weak var sortSegmentedControl: UISegmentedControl!
@IBOutlet weak var langNameSegmentedControl: UISegmentedControl!
fileprivate let managedObjectContext = NSManagedObjectContext.mainQueueContext
fileprivate let managedObjectContext = AppDelegate.persistentContainer.viewContext
weak var delegate: LanguageFilterUpdating?
fileprivate var initialShowLanguageSet = Set<Language>()

View File

@ -136,7 +136,7 @@ class LocalBooksController: UITableViewController, NSFetchedResultsControllerDel
// MARK: - Fetched Results Controller
let managedObjectContext = NSManagedObjectContext.mainQueueContext
let managedObjectContext = AppDelegate.persistentContainer.viewContext
lazy var fetchedResultController: NSFetchedResultsController<Book> = {
let fetchRequest = Book.fetchRequest()
let stateDescriptor = NSSortDescriptor(key: "stateRaw", ascending: true)

View File

@ -49,7 +49,7 @@ extension MainController: UIWebViewDelegate, SFSafariViewControllerDelegate, LPT
// Create article object
guard let url = webView.request?.url,
let article = Article.addOrUpdate(url: url, context: NSManagedObjectContext.mainQueueContext) else {return}
let article = Article.addOrUpdate(url: url, context: AppDelegate.persistentContainer.viewContext) else {return}
article.title = JS.getTitle(from: webView)
article.thumbImagePath = URLResponseCache.shared.firstImage()?.path
self.article = article

View File

@ -38,7 +38,7 @@ class SearchBooksController: SearchTableViewController, UITableViewDelegate, UIT
// MARK: - Fetched Results Controller
let managedObjectContext = NSManagedObjectContext.mainQueueContext
let managedObjectContext = AppDelegate.persistentContainer.viewContext
lazy var fetchedResultController: NSFetchedResultsController<Book> = {
let fetchRequest = Book.fetchRequest()
let langDescriptor = NSSortDescriptor(key: "language.name", ascending: true)

View File

@ -104,7 +104,7 @@ class SearchResultController: SearchTableViewController, UITableViewDataSource,
}
func configureArticleCell(_ cell: ArticleCell, result: SearchResult) {
guard let book = Book.fetch(result.bookID, context: UIApplication.appDelegate.managedObjectContext) else {return}
guard let book = Book.fetch(result.bookID, context: AppDelegate.persistentContainer.viewContext) else {return}
if UIApplication.buildStatus == .alpha {
cell.titleLabel.text = result.title + result.rankInfo
} else {

View File

@ -49,7 +49,7 @@
</dict>
</array>
<key>CFBundleVersion</key>
<string>1.8.2008</string>
<string>1.8.2036</string>
<key>ITSAppUsesNonExemptEncryption</key>
<false/>
<key>LSRequiresIPhoneOS</key>

View File

@ -27,12 +27,6 @@ extension NSFetchedResultsController {
}
}
extension NSManagedObjectContext {
class var mainQueueContext: NSManagedObjectContext {
return (UIApplication.shared.delegate as! AppDelegate).managedObjectContext
}
}
// MARK: - UI
enum BuildStatus {

View File

@ -21,7 +21,7 @@
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.8.2008</string>
<string>1.8.2036</string>
<key>NSExtension</key>
<dict>
<key>NSExtensionMainStoryboard</key>

View File

@ -32,7 +32,6 @@
971A10811D022F74007FC62C /* Pic_P.png in Resources */ = {isa = PBXBuildFile; fileRef = 971A107D1D022F74007FC62C /* Pic_P.png */; };
9722122B1D3FCCE200C0DCF2 /* MainControllerShowHide.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9722122A1D3FCCE200C0DCF2 /* MainControllerShowHide.swift */; };
9726591D1D90A64600D1DFFB /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9726591C1D90A64500D1DFFB /* Notifications.swift */; };
9732075A1DD136A700EDD3DC /* CoreDataContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 973207591DD136A700EDD3DC /* CoreDataContainer.swift */; };
9732075C1DD136BB00EDD3DC /* CoreDataExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9732075B1DD136BB00EDD3DC /* CoreDataExtension.swift */; };
9732079E1DD197EA00EDD3DC /* LibrarySplitViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97C005D71D64B99E004352E8 /* LibrarySplitViewController.swift */; };
9732079F1DD197F400EDD3DC /* CloudBooksController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97C005DB1D64BEFE004352E8 /* CloudBooksController.swift */; };
@ -44,6 +43,7 @@
973207A51DD1984700EDD3DC /* SearchBooksController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97A127C61D777CF100FB204D /* SearchBooksController.swift */; };
973208231DD19C7600EDD3DC /* DownloadProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9726591A1D8DB91200D1DFFB /* DownloadProgress.swift */; };
973208241DD217B600EDD3DC /* BookmarkHUD.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97219DBC1D383A00009FDFF1 /* BookmarkHUD.swift */; };
973208261DD21E9C00EDD3DC /* CoreDataContainer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 973208251DD21E9C00EDD3DC /* CoreDataContainer.swift */; };
9734E54E1D289D060061C39B /* Welcome.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 9734E54D1D289D060061C39B /* Welcome.storyboard */; };
973BCD1A1CEB402900F10B44 /* KiwixTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 973BCD181CEB402900F10B44 /* KiwixTests.swift */; };
973DD40F1D343F2F009D45DB /* libicudata.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 973DD4041D343F2F009D45DB /* libicudata.a */; };
@ -186,8 +186,8 @@
9722122A1D3FCCE200C0DCF2 /* MainControllerShowHide.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = MainControllerShowHide.swift; path = "Kiwix-iOS/Controller/Main/MainControllerShowHide.swift"; sourceTree = SOURCE_ROOT; };
9726591A1D8DB91200D1DFFB /* DownloadProgress.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DownloadProgress.swift; sourceTree = "<group>"; };
9726591C1D90A64500D1DFFB /* Notifications.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Notifications.swift; sourceTree = "<group>"; };
973207591DD136A700EDD3DC /* CoreDataContainer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CoreDataContainer.swift; sourceTree = "<group>"; };
9732075B1DD136BB00EDD3DC /* CoreDataExtension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CoreDataExtension.swift; sourceTree = "<group>"; };
973208251DD21E9C00EDD3DC /* CoreDataContainer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CoreDataContainer.swift; sourceTree = "<group>"; };
9734E54D1D289D060061C39B /* Welcome.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = Welcome.storyboard; path = "Kiwix-iOS/Storyboard/Welcome.storyboard"; sourceTree = SOURCE_ROOT; };
973BCD001CEB3FA500F10B44 /* Kiwix_OSXTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Kiwix_OSXTests.swift; sourceTree = "<group>"; };
973BCD021CEB3FA500F10B44 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
@ -393,8 +393,8 @@
971187891CEB53D700B9909D /* Migration */,
971187881CEB53CE00B9909D /* Classes */,
978C589D1C1CD8750077AE47 /* Properties */,
973207591DD136A700EDD3DC /* CoreDataContainer.swift */,
9732075B1DD136BB00EDD3DC /* CoreDataExtension.swift */,
973208251DD21E9C00EDD3DC /* CoreDataContainer.swift */,
);
path = CoreData;
sourceTree = "<group>";
@ -1125,7 +1125,6 @@
970E7F831DA0305000741290 /* WelcomeController.swift in Sources */,
97A1FD3B1D6F724E00A80EE2 /* stringTools.cpp in Sources */,
970E7F741D9DB0FC00741290 /* 1.8.xcmappingmodel in Sources */,
9732075A1DD136A700EDD3DC /* CoreDataContainer.swift in Sources */,
973207A01DD1983D00EDD3DC /* DownloadTasksController.swift in Sources */,
97A1FD321D6F723D00A80EE2 /* resourceTools.cpp in Sources */,
971A10321D022AD5007FC62C /* SearchBar.swift in Sources */,
@ -1150,6 +1149,7 @@
97A127CB1D777CF100FB204D /* SearchController.swift in Sources */,
97A1FD261D6F71E200A80EE2 /* ZimReader.mm in Sources */,
97A1FD1C1D6F71D800A80EE2 /* KiwixURLProtocol.swift in Sources */,
973208261DD21E9C00EDD3DC /* CoreDataContainer.swift in Sources */,
97D6813F1D6F712800E5FA99 /* Article+CoreDataProperties.swift in Sources */,
97A1FD171D6F71CE00A80EE2 /* Extension.swift in Sources */,
97D6812E1D6F70DE00E5FA99 /* Kiwix.xcdatamodeld in Sources */,

View File

@ -33,5 +33,21 @@
endingLineNumber = "37">
</BreakpointContent>
</BreakpointProxy>
<BreakpointProxy
BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
<BreakpointContent
shouldBeEnabled = "Yes"
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "Kiwix/CoreData/CoreDataContainer.swift"
timestampString = "500310814.395924"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "14"
endingLineNumber = "14"
landmarkName = "init()"
landmarkType = "7">
</BreakpointContent>
</BreakpointProxy>
</Breakpoints>
</Bucket>

View File

@ -2,18 +2,24 @@
// CoreDataContainer.swift
// Kiwix
//
// Created by Chris Li on 11/7/16.
// Created by Chris Li on 11/8/16.
// Copyright © 2016 Wikimedia CH. All rights reserved.
//
import UIKit
import CoreData
class CoreDataContainer: NSPersistentContainer {
// init() {
// super.init(name: "Kiwix")
// loadPersistentStores { (description, error) in
//
// }
// }
init() {
let modelURL = Bundle.main.url(forResource: "Kiwix", withExtension: "momd")!
let model = NSManagedObjectModel(contentsOf: modelURL)!
super.init(name: "Kiwix", managedObjectModel: model)
loadPersistentStores { (_, _) in }
}
override class func defaultDirectoryURL() -> URL {
let urls = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask)
return urls[urls.count-1]
}
}