Swift51.com
Swift 头像
Swift  2016-01-05 15:30

SwiftRecord

回复:0  查看:4725  感兴趣:6  赞:0  

基于 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))

相关开源代码