我是CoreData的新手,已经阅读了几个教程,但空手而归.大多数教程都集中在从CoreData中获取,以填充一个表视图,这不是我现在所做的.
以下是我在CoreData中设置数据的方式.所有类型均为Double,但日期为NSDate
let appDelegate = (UIApplication.sharedApplication().delegate as AppDelegate) let managedobjectContext = appDelegate.managedobjectContext let entityDescription = NSEntityDescription.entityForName("Meditation",inManagedobjectContext: managedobjectContext!) let meditation = NSManagedobject(entity: entityDescription!,insertIntoManagedobjectContext: managedobjectContext!) meditation.setValue(settings.minutes,forKey: "length") meditation.setValue(settings.warmup,forKey: "warmup") meditation.setValue(settings.cooldown,forKey: "cooldown") meditation.setValue(NSDate(),forKey: "date") // fetch stuff from CoreData var request = NSFetchRequest(entityName: "Meditation") var error:NSError? = nil var results:NSArray = managedobjectContext!.executeFetchRequest(request,error: &error)! for res in results { println(res) }
这是我要做的结果,但我无法访问像.minutes,.date等等.我知道我也没有正确得到最后一个项目,我只是想首先打印对象上的属性.
谢谢!
首先,使用“编辑器 – >创建NSManagedobject在Xcode中创建一个”Meditation.swift“文件
子类…“.生成的文件应该是这样的
子类…“.生成的文件应该是这样的
import Foundation import CoreData class Meditation: NSManagedobject { @NSManaged var length: NSNumber @NSManaged var warmup: NSNumber @NSManaged var cooldown: NSNumber @NSManaged var date: NSDate }
现在您可以直接使用属性而不是键值编码
并创建对象
let meditation = NSEntityDescription.insertNewObjectForEntityForName("Meditation",inManagedobjectContext: managedobjectContext) as Meditation meditation.length = ... meditation.warmup = ... meditation.cooldown = ... meditation.date = NSDate() var error : NSError? if !managedobjectContext.save(&error) { println("save Failed: \(error?.localizedDescription)") }
获取对象时,转换结果
executeFetchRequest()到[Meditation]:
let request = NSFetchRequest(entityName: "Meditation") var error : NSError? let result = managedobjectContext.executeFetchRequest(request,error: &error) if let objects = result as? [Meditation] { for meditation in objects { println(meditation.length) println(meditation.date) // ... } } else { println("fetch Failed: \(error?.localizedDescription)") }
最后,要只获取最新的对象,请添加一个排序描述符
按照日期按降序对结果进行排序,并将结果数限制为一个:
let request = NSFetchRequest(entityName: "Meditation") request.sortDescriptors = [NSSortDescriptor(key: "date",ascending: false)] request.fetchLimit = 1 // ...