Skip to content

Instantly share code, notes, and snippets.

@pokk
Created February 10, 2017 05:50
Show Gist options
  • Save pokk/db38d67d79e2c65c95a8a67da2695fdd to your computer and use it in GitHub Desktop.
Save pokk/db38d67d79e2c65c95a8a67da2695fdd to your computer and use it in GitHub Desktop.
How to use CoreData and comparing with SQLite.

Introduction

Using code data is great!!

CodeData

Benifit

CoreData is not like SQLite that we have to use OC object operation. It's easy to create, save, fetech, remove the data.

Comapre

SQLite

1. Base on C language and it needs to use SQL operation.
2. It's trivial to operate the large data.
3. It's not visualization when using OC.

CoreData

1. It's visualiztion and able to "undo/redo" operation.
2. It's able to be implemented various formats
    * NSSQLiteStoreType
    * NSBinaryStoreType
    * NSInMemoryStoreType
    * NSXMLStoreTyp
3. The official API supported, it's more closer with iOS.
class DataController: NSObject {
var managedObjectContext: NSManagedObjectContext
override init() {
// This resource is the same name as your xcdatamodeld contained in your project.
guard let modelURL = Bundle.main.url(forResource: "YOUR_CORDDATA_NAME", withExtension: "momd") else {
fatalError("Error loading model from bundle")
}
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
fatalError("Error initializing mom from: \(modelURL)")
}
let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = psc
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let docURL = urls[urls.endIndex - 1]
/* The directory the application uses to store the Core Data store file.
This code uses a file named "DataModel.sqlite" in the application's documents directory.
*/
let storeURL = docURL.appendingPathComponent("YOUR_CORDDATA_NAME.sqlite")
do {
try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
} catch {
fatalError("Error migrating store: \(error)")
}
}
// GET
func fetchDataInfo() -> [[String: AnyObject]]? {
var dataList: [[String:AnyObject]]?
let dataFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "DataInfo")
do {
let fetchedData = try self.managedObjectContext.fetch(dataFetch) as! [DataInfo]
let end: Int = tail >= fetchedData.count ? fetchedData.count : tail
// No data can be fetched.
if 0 == end {
return nil
}
dataList = []
for index in (0 ... end - 1) {
dataList?.append([
"age": fetchedData[index].age!,
"time": fetchedData[index].time!,
])
}
} catch {
fatalError("fetchDataInfo bad things happened \(error)")
}
return dataList
}
// SAVE
func seedDataInfo(age: Int, time: Int) -> Bool {
// TODO: Now is save each of the data at once time, this can be proved to save some data at once time.
let entity = NSEntityDescription.insertNewObject(forEntityName: "DataInfo", into: self.managedObjectContext)
entity.setValue(age, forKey: "age")
entity.setValue(time, forKey: "time")
// For closing the file.
do {
try self.managedObjectContext.save()
} catch {
fatalError("seedDataInfo failure to save context: \(error)")
}
return true
}
// REMOVE
func removeDataInfo(startfrom head: Int, endto tail: Int) -> Bool {
let dataFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "DataInfo")
do {
let fetchedData = try self.managedObjectContext.fetch(dataFetch) as! [DataInfo]
let end: Int = tail >= fetchedData.count ? fetchedData.count : tail
if 0 != fetchedData.count {
for index in (head ... end - 1) {
self.managedObjectContext.delete(fetchedData[index])
}
}
// For closing the file.
try self.managedObjectContext.save()
} catch {
fatalError("removeDataInfo bad things happened \(error)")
}
return true
}
}
import Foundation
import CoreData
extension DataInfo {
@NSManaged var age: NSNumber?
@NSManaged var time: NSNumber?
}
import Foundation
import CoreData
@objc(DataInfo)
class DataInfo: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment