2017-05-31 117 views
0

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

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' 

回答

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 
+0

感谢。但我试过它不起作用。错误:终止应用程序由于未捕获的异常“NSInvalidArgumentException”,原因:' - [ProjectPart1.Post标题]:无法识别的选择器发送到实例0x7f8c0f6e5330' –

+0

@آژانسکتاب它与我合作。我已经编辑了答案,试一试, – Anuraj

+0

谢谢,但它没有奏效。与同样的错误 –

相关问题