自定义CoreData Access框架而不是AppDelegate

时间:2015-05-24 11:55:33

标签: ios swift core-data

我在AppDelegate for CoreData中创建了一个自定义框架而不是方法。这是班级:

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()
        }
    }
}
}

当我运行应用程序时,我试图以这种方式访问​​它时崩溃了:

let managedObjectContext = DataAccess.sharedInstance.managedObjectContext

这里有什么不对?我的数据模型名为 - Arduino_SmartHome。这是完整的CoreData崩溃: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}])

1 个答案:

答案 0 :(得分:2)

您的问题似乎是

let sqlitePath = NSString(format: "%@/%@", [containerPath!, "Arduino_SmartHome"])

因为您正在创建一个数组以传递给格式,所以不是一个干净的路径,而是获得数组的描述和null(我也希望这会给你一个编译警告)。

更改为

let sqlitePath = NSString(format: "%@/%@", containerPath!, "Arduino_SmartHome")

所以你正确地传递了路径的两个部分,或者更好的是,使用适当的NSString方法:stringByAppendingPathComponent

let sqlitePath = containerPath.stringByAppendingPathComponent("Arduino_SmartHome")