【问题标题】:Updating Core Data object with Swift使用 Swift 更新 Core Data 对象
【发布时间】:2017-05-31 06:42:24
【问题描述】:

我想更新核心数据记录。首先,我搜索了该记录是否存在。如果存在,如果没有创建新记录,则需要更新它。
最后应该返回一个 Post 实例。
我不知道如何用 setValue 更新它以及如何返回一个帖子实例。因为我用这行代码初始化了post实例:

post = NSEntityDescription.insertNewObjectForEntityForName()

而且我不知道如何为更新版本执行此操作。

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
}

我试过这个,但也没有用。

  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

            }

错误:

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

【问题讨论】:

    标签: ios swift core-data


    【解决方案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
    

    【讨论】:

    • 谢谢。但我试过它没有用。错误:由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[ProjectPart1.Post 标题]:无法识别的选择器发送到实例 0x7f8c0f6e5330”
    • @آژانسکتاب 它对我有用。我已经编辑了答案,也试试看
    猜你喜欢
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 2012-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多