How to access Core Data generated Obj-C classes in test targets?

橙三吉。 提交于 2020-01-11 10:08:10

问题


I have a Core Data / Swift Cocoa application project in Xcode 6 (let's call the project Stuff). I created a Core Data entity called Query and used Xcode to create an NSManagedObject subclass for it.

At that point, Xcode 6 offered to create the bridging header for me, as expected, and created Stuff-Bridging-Header.h. Once I #import "Query.h" in the bridging header, then my model object Query is available in my app target Swift code.

How do I make that Query Core Data object (backed by the Xcode-generated Query.h and Query.m) available to my test target Swift code, StuffTests? I tried manually creating a header file StuffTests-Bridging-Header.h and adding #import "Query.h" to it, but my Swift test class is unable to resolve the Query class.


回答1:


I have a project with CoreData in pure Swift, no bridging header files and tests are working. Here's how I've managed to do:

My project name is cars and I have a NSManagedObject called Car

Car.swift:

Car.swift file Target Membership:

cars.xcdatamodeld Data Model Inspector:




回答2:


You can use NSManagedObject directly in Swift as follows:

class Query : NSManagedObject {
  @NSManaged var attrOne : attrOneType
  // ...
}

Currently Xcode won't generate Swift code for an entity; it still only generates Objective-C which may lead you to a bridging solution. But, you don't need to bridge - just start with the generated Objective-C and write Swift code, with the @NSManaged annotation.




回答3:


Took me a while to figure this out. The ideal solution is to import the bridging header in the test target itself. Go in Build Settings > Swift compiler > Code Generation and give the name of your bridging header. Be careful, the test target is not selected by default. You have to select it in the scrollbar (it's located on the same line as General, info, build Settings, build Phases, and Build Rules). This way, you will have the same bridging header for both your project and your different test targets.



来源:https://stackoverflow.com/questions/24235059/how-to-access-core-data-generated-obj-c-classes-in-test-targets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!