简体   繁体   中英

Swift: CoreData error and how to set up entities and DataModels?

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

  • name
  • age

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.

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.

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)")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM