基于 Core Data 極為輕量、易用的對象持久化工具庫。
import SwiftRecord @objc(Event) class Event: NSManagedObject { @NSManaged var eventID: NSNumber @NSManaged var name: String @NSManaged var type: String @NSManaged var when: NSDate @NSManaged var creator: User @NSManaged var attendess: NSSet }
var event = Event.create() as! Event // Downcasts are necessary, event.type = "Birthday" event.when = NSDate() event.save() // simple save event.delete() // simple delete var properties: [String:AnyObject] = ["name":"productQA","type":"meeting", "when":NSDate()] var meeting = Event.create(properties) as! Event // Remember to downcast
// grab all Events var events = Event.all() as! [Event] // all past events before now var pastEvents = Event.query("when < %@", NSDate()) as! [Event] // specific event, yes we have support for format&arguments. Note, finding specific events return optional vars var thisEvent = Event.find("name == %@ AND when == %@", "productQA", NSDate()) as? Event // Use dictionaries to query too var birthdayEvents = Event.query(["type":"birthday"]) as! [Event] // or NSPredicates var predicate = NSPredicate("type == %@", "meeting") var meetingEvents = Event.query(predicate) as! [Event]
// Events sorted by date, defaults to ascending var events = Event.all(sort: "when") as! [Event] // Descending var descendingEvents = Event.all(sort:["when":"DESC"]) as! [Event] // or var descEvents = Event.all(sort:"when DESC, eventID ASC") // All meeting events sorted by when desc and eventID ascending and limit 10 var theseEvents = Event.query(["type":"meeting"], sort:["when":"DESC","eventID":"ASC"], limit: 10) as! [Event] // NSSortDescriptor as sort arg (or array of NSSortDescriptors Event.all(sort: NSSortDescriptor(key:"when",ascending:true))