This is for XCode 6 and Swift...
I'm trying to make a fetch request to the managed object context but it's not returning the correct subclass.
I have already set the subclass in the data model data modeler configuration to the name of my custom subclass and in the code, it is extending the NSManagedObject class.
Any ideas?
Just figured out the solution.
I had to add the #objc attribute to allow the class to be compatible with Objective-C.
Now the fetch request is returning a correct result of Tasks[]
import Foundation
import CoreData
#objc(Task) // make compatible with objective-c
class Task : NSManagedObject
{
#NSManaged var note: String!
#NSManaged var completed: Bool
}
Reference: https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html#//apple_ref/doc/uid/TP40014216-CH4-XID_36
Using #objc(Task) seems to be working but you could also just edit the data model data modeler configuration to the name ToDoList.Task instead of just Task. That will work too and avoid Class conflicts if Task is used anywhere else in the Objective-C code.
Check to make sure that in the "Entity" inspector (right side of the screen, Utilities pane) when Task is selected in your Model that its Class field is properly filled in with "Task" (it's blank by default).
Related
Using Xcode 12, and starting with the default XIB-based swift desktop app, I add a Model class, descended from NSObject with a single stringValue property. In the XIB file I instantiate the Model class, and add a text field to the default window, and bind the value of the text field to the stringValue property of my Model instance. The project builds and runs, and any value I set in the initializer of the Model class displays in the text field.
Here is my Model class:
import Foundation
#objc public class Model : NSObject {
#objc dynamic public var stringValue: NSString
override init() {
stringValue = "some string"
}
}
The full project is available here:
https://github.com/thomasmarschall/KvoLab2023
I started with a bit more complicated setup involving a separate library and framework, but my current setup seems to be super straightforward.
Having done all of this, Xcode displays a grey flag in the Model Key Path field of the text field value binding, and the tool tip for the flag reads "xcode cannot resolve the entered keypath". Also, the autocomplete in the key path field does not work. How can I resolve these issues? Any help would be appreciated.
Working with coredate I used the option codegen: category/extension to be able to create a file where I can put in the re-usable code for finding, updating or deleting database entries.
I started the coredata entity first with the codegen option Class Definition and changed it to category/extension in a later stage.
Now I run against a compile error:
'Property cannot be declared public because its type uses an internal type'
The file name is a generated swift file called:
Gameresults+Coredataproperties.swift
I got the error on the player: TournamentPlayer?
player and round are both relations to another entity.
import Foundation
import CoreData
extension GameResults {
#nonobjc public class func fetchRequest() -> NSFetchRequest<GameResults> {
return NSFetchRequest<GameResults>(entityName: "GameResults")
}
#NSManaged public var earnedRankingPoints: Int16
#NSManaged public var framePoints: Int16
#NSManaged public var highestBreak: Int16
#NSManaged public var isWon: Bool
#NSManaged public var player: TournamentPlayer?
#NSManaged public var round: Rounds?
}
I could not believe that the error did come out of swift so I tried the clean build folder option, saving file, exiting XCode, etc. Nothing worked.
Any tips where to look at how to fix this?
Use the Manual/None option for the codegen.
There are a couple of things that you should consider here.
when you use codegen it automatically creates all classes which are equivalent to your entities as public. I assume TournamentPlayer class is not public and you have definded it yourself. so based on default definition it is internal and the compiler gives you the error correctly. the only thing you can do here is changing the access level and because you're using the codegen and it means you want to change your model, so it's better to change your TournamentPlayer to public. Although it depends on the architecture of your application.
The codegen is automatically regenrated whenever you change your model and is saved in DerivedData.
If you want to take care of it yourself you set it to manual and you handle the code generation yourself manually.
check this article, it gives you a better understanding of codegen https://useyourloaf.com/blog/core-data-code-generation/
one more thing, when you change to manual/none you have to do a clean build otherwise it still uses the generated code in DerivedData
I have created 2 core data entities and then created NSManagedObject Subclasses for them from the editor menu.
However when I run my app I get errors on every line of all the files for some reason.
Here is an example, these errors are the same for both entities created files.
File Code was auto generated so i can apste it here but not sure of its use
import Foundation
import CoreData
extension UserExercise {
#nonobjc public class func fetchRequest() -> NSFetchRequest<UserExercise> {
return NSFetchRequest<UserExercise>(entityName: "UserExercise");
}
#NSManaged public var id: Int16
#NSManaged public var name: String?
#NSManaged public var reps: Int16
#NSManaged public var sets: Int16
#NSManaged public var weight: Int16
#NSManaged public var relationship: NSSet?
}
// MARK: Generated accessors for relationship
extension UserExercise {
#objc(addRelationshipObject:)
#NSManaged public func addToRelationship(_ value: UserRoutine)
#objc(removeRelationshipObject:)
#NSManaged public func removeFromRelationship(_ value: UserRoutine)
#objc(addRelationship:)
#NSManaged public func addToRelationship(_ values: NSSet)
#objc(removeRelationship:)
#NSManaged public func removeFromRelationship(_ values: NSSet)
}
Errors are:
Command/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
Invalid redeclaration of 'UserRoutine'
'UserExercise' is ambiguous for type lookup in this context
#NSManaged only allowed on an instance property or method
Theres too many to list its basically these repeated over and over
Xcode by default manage generation of these subclasses for you. If you want to manage generation of them yourself then:
Select your entities in the data model.
Find Codegen in the utilities pane(right pane) and set it to Manual/None.
Clean and build.
The current default in Xcode is to automatically create subclasses of NSManagedObject for you in the /Users/<your user name>/Library/Developer/Xcode/DerivedData/AppName-agkwmibzbopevjgfajlcbyixzyev/Build/Intermediates/AppName.build/Debug-iphonesimulator/AppName.build/DerivedSources/CoreDataGenerated/Modeldirectory; The DerivedData directory is where Xcode saves automatically generated code. You are redeclaring the same subclass by doing Editor>Create NSManagedObject Subclass... that is why you are getting the "Invalid redeclaration of 'UserRoutine' 'UserExercise' is ambiguous for type lookup in this context #NSManaged only allowed on an instance property or method" error. To resolve the errors and manually create a subclass of NSManagedObjects what you need to do is:
Open terminal and navigate to /Users/<your user name>/Library/Developer/Xcode/DerivedData/AppName-agkwmibzbopevjgfajlcbyixzyev/Build/Intermediates/AppName.build/Debug-iphonesimulator/AppName.build/DerivedSources/CoreDataGenerated/Model
Run this command: rm -rf * (now be careful with this command, run it only when you get to the final directory where the generated codes are or you'll break your project for good)
Delete your current data model
Create a new data model
Select your new data model's entity (do this for each entity within the data model) and go to its attributes inspector and set its Codegen to Manual/None Before the first run after you have created a new data model.
Create a subclass of NSManagedObject by going to Editor>Create NSManagedObject Subclass...
Your errors should disappear.
Hope this helped!
A simple approach that worked for me .... You can find these by choosing an entity and clicking on the Data Model Inspector at the top right . Do this for all of your entities
Its important to FIRST set Module to "Current Product Module" AND Codegen to "Manual/None"
Only then, SECOND: Editor -> Create NSManagedObject subclass.
This is for Swift 3.0 and Xcode 8.2.1(8C1002)
Not sure why you would manually navigate to the project when you can just instead delete the files directly from Xcode.
Find all of your generated files from the xcdatamodeld, inside of your project navigator. Delete all of the files and make sure you move to trash, do not remove references otherwise you're going to have to manually delete the files from:
/Users//Library/Developer/Xcode/DerivedData/AppName-agkwmibzbopevjgfajlcbyixzyev/Build/Intermediates/AppName.build/Debug-iphonesimulator/AppName.build/DerivedSources/CoreDataGenerated/Model
Ok so after you've deleted the files, open your xcdatamodeld, select all of your entities, and in the Utilities panel, select Data Model Inspector button, and make sure that Codegen is set to "Manual/None".
Select your xcdatamodeld and make sure that that Codegen is set to "Manual/None"
Keep all of your entities selected and click Editor > Create NSManagedObject Subclass, make sure to select the folder and drag and drop your generated files in your Model sub-group and your Generated sub-group.
This worked for me and it should work for you too.
I hope that I have helped you.
I also ran into this bug. I fixed it by deleting the old generated entity subclasses and creating it again and for the group I selected the workspace instead of the project or folder in the project, and the subclasses got saved above the project file. It looks weird but it fixed the issue. Also if i move the files into the folder inside the project the error reappears.
I ran into this issue during unit testing due to recreating my NSPersistentContainer over and over again in every unit test. It looks like loading the same managed object model repeatedly could lead to this.
My resolution was to use a single shared instance across all of my unit tests and do clean up between them accordingly.
I was getting the "... is ambiguous for type lookup in this context" error when building a simple SwiftUI Mac app for testing this issue after running Editor/Create NSManagedObject subclass..." with Xcode Version 13.4 (13F17a) on macOS Monterey 12.3.1.
I found a solution in deselecting/unchecking the checkbox for "Targets" in the final dialog before clicking "Create". This checkbox was selected by default. Clearing it and clicking "Create" resulted in a successful build.
This results with the subclass files at the top level of the project structure:
I have an Objective-C model class MyType. This class is used in Swift code:
NSEntityDescription.insertNewObjectForEntityForName("MyType", inManagedObjectContext: context) as! MyType
The as! cast results in the error message
Core Data: Could not cast value of type 'MyType_MyType_2' (0x7be99a30) to MyType (0xf33db74).
If I cast it as NSManagedObject it works. When I print the result, I can nevertheless see, that it is an actual instance of MyType:
<MyType: 0x7ae06d50> (entity: MyType; id: 0x7aeba6d0 <x-coredata:///MyType/t957F2860-85F8-46E0-B6D6-4D1DF6C4EC613> ; data: {
...the fields...
})
What is happening here? And where does the name MyType_MyType_2 come from?
When I had this issue, it was because I had forgotten to set the "class" on the entity. This is what I came up with:
Click on .xcdatamodelId file in your file structure/project
navigator pane (far left).
Select the entity that you are having issues with.
In the Utilities pane (far right), look for the icon that looks like a 1997 cell phone, the Data Model Inspector.
Under the entity settings, you should see two fields, "Name" and "Class" - set up "Class" with the name of the class you are using (typically the same as "Name").
You'll even notice before you follow these steps that the default "class" is NSObject, reflecting the error message. I found some programatic ways to do this too, but this seemed like the simplest/quickest solution.
I should note that my model WAS written in Swift, so I did have to add the #objc(Entity) interoperability reference mentioned by #zellb. But that shouldn't make a difference in the solution as long as you are doing that part properly (and that would cause a different unrelated error from my understanding).
Set Entity Class Name
Set Module "Current Product Module" like below
just try this:
#objc(MyType)
public class MyType: NSManagedObject {
// your class
}
instead of this:
class MyType: NSManagedObject {
// your class
}
I had mistakenly set a "parent entity" in one of my entities in the data model inspector in the entity section. I mistakenly thought that referred to the destination of a one-to-many relationship.
Setting it back to "no parent entity" fixed the problem, although I did have to delete and reinstall the app in the simulator to deal with the messed up core data database.
I'm having trouble working out the implications of this note from Apple's "Using Swift with Cocoa and Objective-C":
Swift classes are namespaced—they’re scoped to the module (typically, the project) they are compiled in. To use a Swift subclass of the NSManagedObject class with your Core Data model, prefix the class name in the Class field in the model entity inspector with the name of your module.
I've done that, using my own application and just the stock master-detail template, so my entity's name is "Event" and its class is "Stock_Master_Detail.Event". When I then choose Create NSManagedObject Subclass from the Editor menu, and ask it to create a Swift subclass, it doesn't name the class right. Xcode creates a file called "Stock_Master_Detail.swift" with that's for a class called Stock_Master_Detail. And if I create multiple entities, all with the module name prefixed, Xcode can't generate more than one subclass since they'll all wind up having the same name.
I'll add that everything works fine in my limited testing if I just omit the module name entirely, counter to Apple's documentation. My question, then, is, what are the implications of not adding the module name to my class?
One way I got around this is to leave the data model file alone, so in this case the class would be "Event". Then in the code where the NSManagedObjectModel is created (AppDelegate if you used Apple's project template) I changed it to:
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle(forClass: self.classForCoder).URLForResource("Model", withExtension: "momd")!
var bundleModel = NSManagedObjectModel(contentsOfURL: modelURL)!
var objectModel = NSManagedObjectModel()
objectModel.entities = bundleModel.entities.map { ( entity ) -> NSEntityDescription in
var entityCopy = entity.copy() as NSEntityDescription
entityCopy.managedObjectClassName = "Stock_Master_Detail." + entity.managedObjectClassName
return entityCopy
}
return objectModel
}()
One improvement, I would like to figure out is how to find the module name dynamically. I know I could parse the current class's name, but that feels a weirder than I want.
I believe that it could be a bug with Swift/Core Data. First, generate your managed object without the module name(prefix). After it is generated, then go back and add the prefix in core data.