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

CoreValue

回复:0  查看:4990  感兴趣:11  赞:1  

CoreValue是Core Data的轻量级封装框架。它也包含了一些简单的抽象,便于查询,更新,保存和删除。

  • 继承类

01struct Shop: CVManagedPersistentStruct {
02 
03        // The name of the CoreData entity
04        static let EntityName = "Shop"
05 
06        // The ObjectID of the CoreData object we saved to or loaded from
07        var objectID: NSManagedObjectID?
08 
09        // Our properties
10        let name: String
11        var age: Int32
12        var owner: Owner?
13 
14        // Create a Value Type from a NSManagedObject
15        // If this looks too complex, see below for an explanation and alternatives
16        static func fromObject(o: NSManagedObject) -> Unboxed<Shop> {
17            return curry(self.init)
18                <^> o <|? "objectID"
19                <*> o <| "name"
20                <*> o <| "age"
21                <*> o <|? "owner"
22        }
23    }

  • 创建、保存、删除

01// Get all shops (`[Shop]` is required for the type checker to get your intent!)
02let shops: [Shop] = Shop.query(self.context, predicate: nil)
03 
04// Create a shop
05let aShop = Shop(name: "Household Wares", age: 30, owner: nil)
06 
07// Store it as a managed object
08aShop.save(self.context)
09 
10// Change the age
11aShop.age = 40
12 
13// Update the managed object in the store
14aShop.save(self.context)
15 
16// Delete the object
17aShop.delete(self.context)
18 
19// Convert a managed object into a shop (see below)
20let nsShop: Shop? = Shop.fromObject(aNSManagedObject).value
21 
22// Convert a shop into an nsmanagedobject
23let shopObj = nsShop.mutatingToObject(self.context)

  • 查询

1// With Sort Descriptors
2public static func query(context: NSManagedObjectContext, predicate: NSPredicate?, sortDescriptors: Array<NSSortDescriptor>) -> Array
3 
4// Without sort descriptors
5public static func query(context: NSManagedObjectContext, predicate: NSPredicate?) -> Array

相关开源代码