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

CoreValue

回复:0  查看:4784  感兴趣:11  赞: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
    aShop.save(self.context)

    // Change the age
    aShop.age = 40

    // Update the managed object in the store
    aShop.save(self.context)

    // Delete the object
    aShop.delete(self.context)

    // 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

相关开源代码