Baseduo
Baseduo

Reputation: 55

How to load basic initial and unique data to Core Data in Swift?

I am working on a project and would like to have some initial data loaded to Core Data. There are two attributes in the Core Data. First belongs to body part and second belongs to its property. Such as Eyes to have one of the four colors and so forth. The data will be like following:

Eyes Blue

Eyes Brown

Eyes Green

Eyes Black

Hair Red

Hair Brunette

Hair Blonde

Clothes Dress

Clothes Skirt

Clothes Shoes

Clothes Hat

Clothes Gloves

I have searched some CSV or pList versions and heard some sqLite shipment alternatives but couldn't figure out how to do them effectively.

I appreciate any clear explanation to load small initial data to Core Data and also removing any duplicate value from Core Data, if exists. Thank you in advance.

Upvotes: 0

Views: 325

Answers (1)

Dorian Roy
Dorian Roy

Reputation: 3104

Here is some very basic code to show one simple way of doing this.

You need to add your own identifier attribute so you can check if an item already exists. Let's say you call that id. Then, when you start your app, you check for each of your default values and if they don't already exist, add them, like this:

// create a fetch request to get all items with id=1
let fr = NSFetchRequest<MyItem>(entityName: MyItem.entity().name!)
fr.predicate = NSPredicate(format: "id == %@", "1")
do {
    // if that request returns no results
    if (try myManagedObjectContext.fetch(fr).isEmpty == true) {
        // create the default item
        let item = NSEntityDescription.insertNewObject(forEntityName: MyItem.entity().name!, into: myManagedObjectContext) as! MyItem
        // set the id
        item.id = "1"
        // set other attributes here
    }
} catch {
    // fetching failed, handle the error
}

After adding the data, you have to save it:

// save the context
do {
    try myManagedObjectContext.save()
} catch {
    // handle the error
}

You could also use Core Datas Unique Constraints, but I think this solution is much simpler. Hope this helps!

Upvotes: 1

Related Questions