我正在制作一个sprite kit游戏,需要保存三个整数:currentLevel,maxLevelReached和highScore。我也想对iCloud实施这些,但这对我来说是另一个步骤,首先我想弄清楚我现在遇到的问题。基本上,我正在尝试使用核心数据来存储它们。在我的app委托中,我添加了以下内容(基本上我创建了新项目并复制了核心数据代码)
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = NSBundle.mainBundle().URLForResource("GameState", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("APPNAME.sqlite")
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)
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
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()
}
}
}
当我这样做时,我创建了我的数据模型(File-> new-> CoreData-> Data model)并将其命名为GameState。然后我创建了名为CurrentLevel的实体,并添加了Int16类型的属性并命名为currentLevel。我创建了类Appname.CurrentLevel的实体。然后,在我的游戏场景中,我添加了以下属性:
var currentLevel = [NSManagedObject]()
var levelToShow: Int16!
并创建了这两个函数来处理核心数据。
//Handling the fetching from the CoreData
func fetchTheStuff() {
//1
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
//2
let fetchRequest = NSFetchRequest(entityName:"CurrentLevel")
//3
var error: NSError?
let fetchedResults =
managedContext.executeFetchRequest(fetchRequest,
error: &error) as? [NSManagedObject]
if let results = fetchedResults {
currentLevel = results
println(currentLevel)
} else {
println("Could not fetch \(error), \(error!.userInfo)")
}
}
//Handling the saving
func saveCurrentLevel(cLevel: Int16){
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
let entity = NSEntityDescription.entityForName("CurrentLevel",
inManagedObjectContext:
managedContext)
let curLevel = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext:managedContext)
curLevel.setValue(name, forKey: "currentLevel")
var error: NSError?
if !managedContext.save(&error) {
println("Could not save \(error), \(error?.userInfo)")
}
}
正如您所看到的,fetch功能仍处于测试阶段(我只是打印结果)。如果我第一次使用应用程序时获取它,它会给我一个空字符串,因为它应该是。但是,如果我尝试使用保存功能保存数字然后获取内容,则日志屏幕会给出以下警告:
CoreData:警告:无法为实体“CurrentLevel”加载名为“appname.CurrentLevel”的类。找不到类,而是使用默认的NSManagedObject。
知道我想要实现的功能,看到我尝试使用的方法,有没有人知道如何解决我的问题?
P.S。此外,似乎这整个核心数据的内容非常复杂,即使我阅读了很多关于它的内容,我也很难掌握它是如何工作的。因此,如果有人建议降低复杂性以获得相同的结果(因此,不使用任何功能),那么提示非常受欢迎。
答案 0 :(得分:0)
回答最初的问题 请确保为您的Coredata模型生成正确的类,突出显示您的实体,然后选择编辑器 - >创建NSObject 子类