2017-05-31 54 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

謝謝,但它沒有奏效。與同樣的錯誤 –