我怎么能够转换到NSManagedObject但不是我的实体的类型? [英] How come I can cast to NSManagedObject but not to my entity's type?

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

问题描述

我在一个全新的项目中使用了Swift样板代码。我的 .xcdatamodeld 文件具有单个实体(任务),



我有一个 Task.swift 文件,如下所示:

  import CoreData 

class任务:NSManagedObject {
@NSManaged var name:String
}

当我运行时,它的工作原理:

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

firstTask.setPrimitiveValue TPS报告,forKey:name)

var错误:NSError?

managedObjectContext.save(& error)



但是,当我运行完全相同的代码,但是使用作为任务而不是作为NSManagedObject ,我得到一个崩溃与错误消息线程1:EXC_BREAKPOINT(代码= EXC_I386_BPT ,subcode = 0x0),与 var firstTask ...行相关联。如果我继续执行,每次我提前它,我在线程1的顶部获得 EXC_BAD_ACCESS 0 misaligned_stack_error _ 。 / p>

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

解决方案

您的类名字段实际上是模块 .Task,其中模块是您的应用程序的名称。 Swift中的CoreData类是命名空间。现在,你的对象被作为一个NSManagedObject而不是一个任务从上下文中拉出来,所以as-cast是失败的。


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).

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)

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

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?

解决方案

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天全站免登陆