I am newbie into IOS development and tumbled on working with coredata.

I have created an AppPage entity with pageId attribute in it marked as an unique constraint.

Now i can insert a row into AppPage using below code:

let context =  getAppDelegate().persistentContainer.viewContext


    let appPage = AppTable(context: context)

    appPage.pageId = 12
    appPage.pContent = "Hello ManiKanta"


    do{
        try getAppDelegate().persistentContainer.viewContext.save()

        print("saved successfully")
    }catch{
        print("error while saving")
    }

Now when what i want here is that if again a row with pageId as 12 and pContent as New updated information the same row in the entity should get updated with the updated information.

I googled to and found out that

getAppDelegate().persistentContainer.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy

but setting NSMergeByPropertyObjectTrumpMergePolicy is giving me an compilation error in my XCode(v8.3.2)

Basically insert a row if it is not existing, else update the row with given id.

Here is the compilation error thrown by Xcode.

Use of unresolved identifier NSMergeByPropertyObjectTrumpMergePolicy

2

There are 2 answers

1
pesch On

You need to fetch for an AppTable with that pageId. If you find one, use the data you have to update it. If you find none, create a new one like you show in your question. If you find many, you have an error to deal with.

In your case:

let context =  getAppDelegate().persistentContainer.viewContext
let request: NSFetchRequest<AppTable> = NSFetchRequest(entityName: "AppTable")
let fetchId = 12
request.predicate = NSPredicate(format: "pageId == %d", fetchId)
    do {
        let fetched = try context?.fetch(request)
        // you should find 1
        if fetched?.count == 1 {
            print("same pageId: /(fetchId)")
            // you can update it here if you want
        } else if fetched?.count == 0 {
            // There is no AppTable with this id so create a new one
            let appPage = AppTable(context: context)
            // Populate all the properties here and save
            // ...
1
Tom Harrington On

Since you're using Swift, the name is different. Instead of NSMergeByPropertyObjectTrumpMergePolicy, you should use NSMergePolicyType.mergeByPropertyObjectTrumpMergePolicyType. It's the same thing with a different name when using Swift.