Swift 头像
Swift  2016-01-05 15:47


回复:0  查看:3872  感兴趣:9  赞:1  

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

  • 继承类

struct Shop: CVManagedPersistentStruct {

        // The name of the CoreData entity
        static let EntityName = "Shop"

        // The ObjectID of the CoreData object we saved to or loaded from
        var objectID: NSManagedObjectID?

        // Our properties
        let name: String
        var age: Int32
        var owner: Owner?

        // Create a Value Type from a NSManagedObject
        // If this looks too complex, see below for an explanation and alternatives
        static func fromObject(o: NSManagedObject) -> Unboxed<Shop> {
            return curry(self.init)
                <^> o <|? "objectID"
                <*> o <| "name"
                <*> o <| "age"
                <*> o <|? "owner"

  • 创建、保存、删除

    // Get all shops (`[Shop]` is required for the type checker to get your intent!)
    let shops: [Shop] = Shop.query(self.context, predicate: nil)

    // Create a shop
    let aShop = Shop(name: "Household Wares", age: 30, owner: nil)

    // Store it as a managed object

    // Change the age
    aShop.age = 40

    // Update the managed object in the store

    // Delete the object

    // Convert a managed object into a shop (see below)
    let nsShop: Shop? = Shop.fromObject(aNSManagedObject).value

    // Convert a shop into an nsmanagedobject
    let shopObj = nsShop.mutatingToObject(self.context)

  • 查询

// With Sort Descriptors
public static func query(context: NSManagedObjectContext, predicate: NSPredicate?, sortDescriptors: Array<NSSortDescriptor>) -> Array

// Without sort descriptors
public static func query(context: NSManagedObjectContext, predicate: NSPredicate?) -> Array