Reputation: 5635
I created a custom framework instead of methods in AppDelegate for CoreData. Here's the class:
public class DataAccess: NSObject {
public class var sharedInstance: DataAccess {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: DataAccess? = nil
}
dispatch_once(&Static.onceToken, {
Static.instance = DataAccess()
})
return Static.instance!
}
// MARK: - Core Data stack
public lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.sergiizernov.Arduino_SmartHome" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
public 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("Arduino_SmartHome", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
public 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
let containerPath = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.com.sergiizernov.Arduino-SmartHome")!.path
let sqlitePath = NSString(format: "%@/%@", [containerPath!, "Arduino_SmartHome"])
let url = NSURL(fileURLWithPath: sqlitePath as String)
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
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
public 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()
}
}
}
}
When I run application I got crash when trying to access it this way:
let managedObjectContext = DataAccess.sharedInstance.managedObjectContext
What is it wrong here? My data model is named - Arduino_SmartHome
. Here's complete CoreData crash: 2015-05-24 14:55:21.189 Arduino SmartHome[36241:3288244] CoreData: error: -addPersistentStoreWithType:SQLite configuration:(null) URL:(%0A%20%20%20%20%22/Users/nikitazernov/Library/Developer/CoreSimulator/Devices/2EC83E9B-E9C5-4200-920B-4E8644797919/data/Containers/Shared/AppGroup/1A5E4895-19FF-45E0-807A-C44995AF06F7%22,%0A%20%20%20%20%22Arduino-SmartHome%22%0A)/(null) -- file:/// options:(null) ... returned error Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)" UserInfo=0x7fdcea7639c0 {reason=Failed to create file; code = 2} with userInfo dictionary {
reason = "Failed to create file; code = 2";
}
2015-05-24 14:55:21.191 Arduino SmartHome[36241:3288244] Unresolved error Optional(Error Domain=YOUR_ERROR_DOMAIN Code=9999 "Failed to initialize the application's saved data" UserInfo=0x7fdcea768f40 {NSLocalizedDescription=Failed to initialize the application's saved data, NSLocalizedFailureReason=There was an error creating or loading the application's saved data., NSUnderlyingError=0x7fdcea7633b0 "The operation couldn’t be completed. (Cocoa error 512.)"}), Optional([NSLocalizedDescription: Failed to initialize the application's saved data, NSLocalizedFailureReason: There was an error creating or loading the application's saved data., NSUnderlyingError: Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)" UserInfo=0x7fdcea7639c0 {reason=Failed to create file; code = 2}])
Upvotes: 1
Views: 233
Reputation: 119021
Your problem appears to be
let sqlitePath = NSString(format: "%@/%@", [containerPath!, "Arduino_SmartHome"])
because you're creating an array to pass to the format so instead of a cleanly formed path you get a description of the array and null (I'd also expect this to be giving you a compilation warning).
Change to
let sqlitePath = NSString(format: "%@/%@", containerPath!, "Arduino_SmartHome")
so you're properly passing both parts of the path, or, better, use the appropriate NSString
method: stringByAppendingPathComponent
let sqlitePath = containerPath.stringByAppendingPathComponent("Arduino_SmartHome")
Upvotes: 2