0

I want to update Core Data records. First, I searched if that record existed. if it exist, it needs to be updated if not a new record is created.
Finally a Post instance should be returned.
I don't know how to update it with setValue and how to return a post instance. Because I initialized the post instance with this line of code:

post = NSEntityDescription.insertNewObjectForEntityForName()

And I don't know how to do this for the updating one.

class Post: NSManagedObject {

}
    var post: Post!


 private static func postFromJSONObject(json: [String:AnyObject], inContext context: NSManagedObjectContext) -> Post? {

   .
   .
   .
    let coreDataStack = CoreDataStack(modelName: "ProjectPart1")
    let mainQueueContext = coreDataStack.mainQueueContext

    let fetchRequest = NSFetchRequest(entityName: "Post")
    fetchRequest.predicate = NSPredicate(format: "id = %@", "\(postID)")
    do {
        let foundRecordsArray = try! mainQueueContext.executeFetchRequest(fetchRequest) as! [Post]

        if foundRecordsArray.count > 0 {
            //here is where I should update Core Data!


        } else{
            context.performBlockAndWait() {
                post = NSEntityDescription.insertNewObjectForEntityForName("Post", inManagedObjectContext: context) as! Post
                post.title = postTitle
                post.body = postBody
                post.id = postID
                post.userId = postUserID
            }
        }
    } catch {
        print("error")
    }
    return post
}

I tried this one but it didn't work either.

  if foundRecordsArray.count > 0 {
                var res = foundRecordsArray[0] as NSManagedObject
                res.setValue(postID, forKey: "id")
                res.setValue(postUserID, forKey: "userId")
                res.setValue(postTitle, forKey: "title")
                res.setValue(postBody, forKey: "body")

                post = res as! Post

            }

Error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ProjectPart1.Post title]: unrecognized selector sent to instance 0x7f8e5180e0b0'

1 Answer 1

1
    fetchRequest.fetchLimit = 1
    var post:Post!
   if let foundRecordsArray = try? mainQueueContext.executeFetchRequest(fetchRequest), foundRecordsArray.count > 0
      {
               post = foundRecordsArray[0]

      } else{            // Create new

         post = NSEntityDescription.insertNewObjectForEntityForName("Post", inManagedObjectContext: context) as! Post               
     }

    post.title = postTitle
    post.body = postBody
    post.id = postID
    post.userId = postUserID
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. but I tried that it didn't work. ERROR: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ProjectPart1.Post title]: unrecognized selector sent to instance 0x7f8c0f6e5330'
@آژانسکتاب It worked with me. I have edited the answer, make a try that too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.