欢迎加入QQ讨论群258996829

SwiftRecord

发布时间:2016-01-05 15:30  回复:0  查看:4673  感兴趣:6  赞:0   最后回复:2016-01-05 15:30  

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

相关开源代码

您还未登录,请先登录

热门帖子

最新帖子