简体   繁体   English

使用Swift更新Core Data对象

[英]Updating Core Data object with Swift

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. 最后,应该返回一个Post实例。
I don't know how to update it with setValue and how to return a post instance. 我不知道如何使用setValue更新它以及如何返回post实例。 Because I initialized the post instance with this line of code: 因为我使用以下代码行初始化了post实例:

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'
    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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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