Created
February 22, 2015 05:00
-
-
Save thecb4/41d5d232802e820acb53 to your computer and use it in GitHub Desktop.
Swift CoreData CRUD
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import CoreData | |
public class CoreDataManager { | |
public var storeType: NSString! | |
public var resource: NSString! | |
// MARK: - Core Data stack | |
init(){} | |
public class var sharedInstance : CoreDataManager { | |
struct Static { | |
static let instance : CoreDataManager = CoreDataManager() | |
} | |
return Static.instance | |
} | |
public func configure(storeType:NSString!,_ resource:NSString!) { | |
self.storeType = storeType; | |
self.resource = resource; | |
} | |
lazy var applicationDocumentsDirectory: NSURL = { | |
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.thecb4.coredataexample" in the application's documents Application Support directory. | |
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) | |
return urls[urls.count-1] as NSURL | |
}() | |
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 = NSBundle.mainBundle().URLForResource(self.resource, withExtension: "momd")! | |
return NSManagedObjectModel(contentsOfURL: modelURL)! | |
}() | |
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { | |
// The persistent store coordinator for the application. This implementation creates and return 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 | |
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) | |
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("\(self.resource).sqlite") | |
var error: NSError? = nil | |
var failureReason = "There was an error creating or loading the application's saved data." | |
if coordinator!.addPersistentStoreWithType(self.storeType, configuration: nil, URL: url, options: nil, error: &error) == nil { | |
coordinator = nil | |
// Report any error we got. | |
let dict = NSMutableDictionary() | |
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" | |
dict[NSLocalizedFailureReasonErrorKey] = failureReason | |
dict[NSUnderlyingErrorKey] = error | |
error = 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 \(error), \(error!.userInfo)") | |
abort() | |
} | |
return coordinator | |
}() | |
public 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 | |
if coordinator == nil { | |
return nil | |
} | |
var managedObjectContext = NSManagedObjectContext() | |
managedObjectContext.persistentStoreCoordinator = coordinator | |
return managedObjectContext | |
}() | |
// MARK: - Core Data Saving support | |
func saveContext () { | |
if let moc = self.managedObjectContext { | |
var error: NSError? = nil | |
if moc.hasChanges && !moc.save(&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. | |
NSLog("Unresolved error \(error), \(error!.userInfo)") | |
abort() | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create | |
let id = Test.create(); | |
// Read One | |
let crudID = NSNumber(integer: 1) | |
let entity:Test? = Test.readOne(crudID); | |
// Read All | |
let entities = Test.readAll() | |
// Update | |
let crudID = NSNumber(integer: 1) | |
var params:[String:AnyObject] = [:] | |
params["strAttribute"] = "Hello World" | |
let updated = Test.updateOne(crudID, params) | |
// Delete | |
let crudID = NSNumber(integer: 1) | |
let deleted = Test.deleteOne(crudID) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import CoreData | |
extension NSManagedObject { | |
public func save() -> Bool { | |
NSManagedObject.stack().saveContext() | |
return true | |
} | |
public class func entityName() -> String! { | |
return NSStringFromClass(self).componentsSeparatedByString(".").last! | |
//return NSStringFromClass(self) | |
} | |
public class func stack() -> CoreDataManager { | |
return CoreDataManager.sharedInstance | |
} | |
public class func count() -> Int { | |
let entityName = self.entityName() | |
println("attempting to count entities of type \(entityName)") | |
let fetchRequest = NSFetchRequest(entityName: entityName) | |
return self.stack().managedObjectContext!.countForFetchRequest(fetchRequest, error: nil); | |
} | |
public class func createEntity<T>() -> T { | |
return NSEntityDescription.insertNewObjectForEntityForName(self.entityName(), inManagedObjectContext: self.stack().managedObjectContext!) as T | |
} | |
public class func create() -> NSNumber { | |
let crudID = NSNumber(integer:self.count() + 1) | |
let object:NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName(self.entityName(), inManagedObjectContext: self.stack().managedObjectContext!) as NSManagedObject | |
object.setValue(crudID, forKey: "crudID") | |
object.save() | |
return object.valueForKey("crudID") as NSNumber | |
} | |
public class func readOne<T>(crudID:NSNumber) -> T? { | |
let fetchRequest = NSFetchRequest(entityName: self.entityName()) | |
let predicate = NSPredicate(format: "crudID = %@", crudID) | |
fetchRequest.predicate = predicate | |
if let entities = self.stack().managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [NSManagedObject] { | |
//if(entities.count != 1) { | |
// abort(); | |
//} | |
if(entities.count == 0) { | |
return nil | |
} | |
return entities[0] as? T; | |
} | |
return nil | |
} | |
public class func readAll() -> [NSManagedObject]? { | |
let fetchRequest = NSFetchRequest(entityName: self.entityName()) | |
if let entities = self.stack().managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [NSManagedObject] { | |
return entities; | |
} | |
return nil | |
} | |
public class func updateOne(crudID:NSNumber, _ params:Dictionary<String,AnyObject>) ->Bool { | |
if let entity:NSManagedObject = self.readOne(crudID) { | |
for (key,value) in params { | |
entity.setValue(value, forKey: key) | |
} | |
self.stack().saveContext() | |
return true | |
} | |
return false | |
} | |
public class func deleteOne(crudID:NSNumber) -> Bool { | |
if let entity:NSManagedObject = self.readOne(crudID) { | |
self.stack().managedObjectContext?.deleteObject(entity) | |
self.stack().saveContext() | |
return true | |
} | |
return false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment