2016-07-14 29 views
0

在我的使用核心數據保存用戶歷史記錄的應用程序中,一切都按預期工作,我需要在用戶點擊自定義按鈕時更新一行值。Swift:使用核心數據更新一行[indexPath.row]

// reverse file lock status 
@IBAction func reverseLockStatus(sender: AnyObject) { 

    var indexPath: NSIndexPath! 

    if let superview = sender.superview { 
     if let cell = superview!.superview as? CustomTableViewCell { 
      indexPath = tableView.indexPathForCell(cell) 
     } 
    } 




    //1 
    let appDelegate = 
     UIApplication.sharedApplication().delegate as! AppDelegate 

    let managedContext = appDelegate.managedObjectContext 

    let entity = NSEntityDescription.entityForName("DownloadHistory", 
                inManagedObjectContext:managedContext) 

    let record = NSManagedObject(entity: entity!, 
           insertIntoManagedObjectContext: managedContext) 

    //2 
    let fetchRequest = NSFetchRequest(entityName: "DownloadHistory") 

    fetchRequest.predicate = NSPredicate(format: "id == %@", indexPath.row) 


    //3 
    record.setValue(false, forKey: "isLocked") 

    try! managedContext.save() 


    //self.tableView.reloadData() 

} 

我構建了fetchRequest來獲取想要的行,我不知道如何設置/保存更新值爲False。

+0

檢查本教程:https://softwarejuancarlos.com/2015/12/19/swift-2-examples-9-core-data-create-get-update-and-remove-entities/ –

回答

0

您可以將對象轉換爲NSManagedObject子項,在您的情況下爲'DownloadHistory',並直接使用屬性。

let record = NSManagedObject(entity: entity!, 
           insertIntoManagedObjectContext: managedContext) as! DownloadHistory 

record.isLocked = false 
+0

雖然這段代碼可以回答這個問題,提供關於如何和/或爲什麼解決問題會提高答案的長期價值的附加背景。 – HiDeo