为什么我可以转换为 NSManagedObject 但不能转换为我的实体类型? [英] How come I can cast to NSManagedObject but not to my entity's type?

查看:17
本文介绍了为什么我可以转换为 NSManagedObject 但不能转换为我的实体类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个新项目中将 Swift 样板代码用于 Core Data.我的 .xcdatamodeld 文件定义了一个实体(Task)和一个属性(name).

I'm using the Swift boilerplate code for Core Data in a fresh project. My .xcdatamodeld file has a single entity defined (Task) with a single attribute (name).

我有一个 Task.swift 文件,看起来像这样:

I have a Task.swift file that looks like this:

import CoreData

class Task: NSManagedObject {
    @NSManaged var name: String
}

当我运行它时,它可以工作:

When I run this, it works:

var firstTask = NSEntityDescription.insertNewObjectForEntityForName("Task",
    inManagedObjectContext: managedObjectContext) as NSManagedObject

firstTask.setPrimitiveValue("File my TPS reports", forKey: "name")

var error: NSError?

managedObjectContext.save(&error)

我什至可以进入 iOS 模拟器使用的 SQLite 数据库并确认该行已添加.

I can even go into the SQLite database being used by the iOS simulator and confirm that the row was added.

但是,当我运行与上面完全相同的代码但使用 as Task 而不是 as NSManagedObject 时,我会崩溃并显示错误消息 Thread 1: EXC_BREAKPOINT (code=EXC_I386_BPT, subcode=0x0),与 var firstTask... 行相关联.如果我继续执行,每次推进线程 1 时,都会在线程 1 的顶部得到 EXC_BAD_ACCESS0 misaligned_stack_error_.

However, when I run the exact same code as above but with as Task instead of as NSManagedObject, I get a crash with the error message Thread 1: EXC_BREAKPOINT (code=EXC_I386_BPT, subcode=0x0), associated with the var firstTask… line. If I continue execution, I get EXC_BAD_ACCESS and 0 misaligned_stack_error_ at the top of Thread 1 each time I advance it.

为什么这个演员会导致这一切?

Why might this cast lead to all this?

推荐答案

确保您的类名称字段实际上是 Module.Task,其中 Module 是您的名称应用程序.Swift 中的 CoreData 类是命名空间的.现在,您的对象正在作为 NSManagedObject 而不是作为任务从上下文中拉出,因此 as-cast 失败.

Make sure your Class name field is actually Module.Task, where Module is the name of your app. CoreData classes in Swift are namespaced. Right now, your object is being pulled out of the context as an NSManagedObject, not as a Task, so the as-cast is failing.

这篇关于为什么我可以转换为 NSManagedObject 但不能转换为我的实体类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆