gpt4 book ai didi

ios - 自定义 CoreData 访问框架而不是 AppDelegate

转载 作者:行者123 更新时间:2023-11-28 05:27:44 26 4
gpt4 key购买 nike

我在 AppDelegate 中为 CoreData 创建了一个自定义框架而不是方法。这是类(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()
}
}
}
}

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

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) ...返回错误 Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn't be已完成。(Cocoa 错误 512。)"UserInfo=0x7fdcea7639c0 ​​{reason=创建文件失败; code = 2} with userInfo dictionary {
reason = "创建文件失败;code = 2";
}
2015-05-24 14:55:21.191 Arduino SmartHome[36241:3288244] Unresolved 错误可选(错误域=YOUR_ERROR_DOMAIN 代码=9999“无法初始化应用程序的保存数据”UserInfo=0x7fdcea768f40 {NSLocalizedDescription=无法初始化应用程序的保存数据, NSLocalizedFailureReason=创建或加载应用程序保存的数据时出错。, NSUnderlyingError=0x7fdcea7633b0 “操作无法完成。(Cocoa 错误 512。)”}), Optional([NSLocalizedDescription: 无法初始化应用程序的保存数据, NSLocalizedFailureReason: 创建或加载应用程序保存的数据时出错。, NSUnderlyingError: Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn't be completed. (Cocoa error 512.)"UserInfo=0x7fdcea7639c0 ​​{reason=Failed to create文件;代码 = 2}])

最佳答案

你的问题似乎是

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

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

更改为

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

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

let sqlitePath = containerPath.stringByAppendingPathComponent("Arduino_SmartHome")

关于ios - 自定义 CoreData 访问框架而不是 AppDelegate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30423215/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com