Reputation: 827
So far I can create my own Data Models in a swift file. Something like:
User.swift:
class User {
var name: String
var age: Int
init?(name: String, age: Int) {
self.name = name
self.age = age
}
}
When I create a Core Data model, ie. a UserData entity, (1) do I have to add the same number of attributes as in my own data model, so in this case two - the name and age? Or (2) can it has just one attribute eg. name (and not age)?
My core data model:
UserData
The second problem I have is that when I start the fetch request I get a strange error in Xcode. This is how I start the fetchRequest (AppDelegate is set up like it is suggested in the documentation):
var users = [User]()
var managedObjectContext: NSManagedObjectContext!
...
func loadUserData() {
let dataRequest: NSFetchRequest<UserData> = UserData.fetchRequest()
do {
users = try managedObjectContext.fetch(dataRequest)
....
} catch {
// do something here
}
}
The error I get is "Cannot assign values of type '[UserData] to type [User].
What does this error mean? In the official documentation are some of the errors described, but not this particularly one.
Upvotes: 0
Views: 1000
Reputation: 1138
If you are designing a user model in core data you don't have to write the class yourself. In fact by default Xcode will generate subclasses of NSManagedObject automatically once you create them in your project's, but you can also manually generate them if you would like to add additional functionality:
Then you can go to Editor and manually generate the classes
Doing this will give you User+CoreDataClass.swift
and User+CoreDataProperties.swift
. I see in your question you are asking about how the core data model compares to your 'own' model, but if you're using core data then that IS the model. The generated User class, which subclasses NSManagedObject, is all you need.
Then you might fetch the users like this:
let userFetch = NSFetchRequest(entityName: "User")
do {
users = try managedObjectContext.executeFetchRequest(userFetch) as! [User]
} catch {
fatalError("Failed to fetch users: \(error)")
}
Upvotes: 1
Reputation: 285200
You cannot use custom (simple) classes as Core Data model.
Classes used as Core Data model must be a subclass of NSManagedObject
.
If your entity is named UserData
you have to declare the array
var users = [UserData]()
The User
class is useless.
Upvotes: 0