简体   繁体   English

从CoreData获取并强制转换

[英]Fetching from CoreData and casting

When fetching data from CoreData the results is an array of AnyObjects . 时,取从CoreData数据的结果是阵列AnyObjects When I cast this array to the related class, I can use the data with no problems. 当我将此数组转换为相关类时,可以毫无问题地使用数据。

My question is, I want to do something when the objects are being initialized but I don't know where and when the objects are getting initialised after it has been fetched from CoreData. 我的问题是,我想在初始化对象时执行某些操作,但是我不知道从CoreData提取对象之后何时在何处初始化对象。

A sample of how I get the data from CoreData: 我如何从CoreData获取数据的示例:

let request = NSFetchRequest(entityName: "Buildings")
let results = (try? context.executeFetchRequest(request)) as? [Buildings] ?? []

with my class as: 我的班级为:

class Buildings: NSManagedObject {

    @NSManaged var name: String

    convenience init(context: NSManagedObjectContext, name: String) {
        let description = NSEntityDescription.entityForName("Buildings", inManagedObjectContext: context)!
        self.init(entity: description, insertIntoManagedObjectContext: context)

        self.name = name
    }
}

You need to overwrite awakeFromFetch() method in your Buildings class like 您需要在Buildings类中覆盖awakeFromFetch()方法,例如

func awakeFromFetch() {
    super.awakeFromFetch()
    // do your initialization
}

This method is called on every fetch of the object from the persistent store. 从持久性存储中每次获取对象时都会调用此方法。

What you are talking about is faulting, basically Core Data tries to keep its memory footprint as low as possible and one of the strategies it uses to accomplish this is faulting. 您所谈论的是错误,基本上,Core Data试图将其内存占用量保持在尽可能低的水平,而用于实现此目的的策略之一就是错误。 When you fetch the records for your entity, Core Data executed the fetch request, but it didn't fully initialize the managed objects representing the fetched records. 当您获取实体的记录时,Core Data执行了获取请求,但是并没有完全初始化代表所获取记录的托管对象。

The moment you access an attribute or relationship of a managed object, the fault is fired, which means that Core Data changes the fault into a realized managed object. 一旦访问托管对象的属性或关系,就会触发故障,这意味着Core Data会将故障更改为已实现的托管对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM