2016-09-26 90 views
-1

我想撤銷我最後一次操作。我正在使用此代碼。但我無法做到這一點。請幫助。任何幫助,將apperciated在CoreData中撤消操作

首先我節省紀錄

@IBAction func save(sender: AnyObject) { 
    let appDelegate = 
    UIApplication.sharedApplication().delegate as! AppDelegate   

    let managedContext = appDelegate.managedObjectContext 
    let entity = NSEntityDescription.entityForName("Person", 
     inManagedObjectContext:managedContext) 
    entity!.uniquenessConstraints = [["name"]] 
    let person = NSManagedObject(entity: entity!, 
     insertIntoManagedObjectContext: managedContext) 

    //3 
    person.setValue(first.text, forKey: "name") 
    person.setValue(second.text, forKey: "age") 

    //4 
    do { 
     try managedContext.save() 
     //5 
     people.append(person) 

    } catch let error as NSError { 
     print("Could not save \(error), \(error.userInfo)") 
    }   
} 

然後我想重做

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
    appDelegate.managedObjectContext.undo() 

回答

0

NSManagedObjectContext需要撤消管理器,使撤銷操作。在iOS中,默認情況下(出於性能原因),它沒有一個。

即使它確實(您可以創建並指定一個),您的代碼將無法工作 - 撤消會反轉最新的未提交更改。在你的例子中你已經保存了上下文 - 沒有內置的撤消支持。

鑑於iOS上大多數編輯/插入操作的模態性質,創建一個新的上下文以用作編輯暫存器並將其丟棄(如果用戶打開解除或取消)或保存(如果用戶點擊保存或完成或其他)。

+0

謝謝先生...請發送一些代碼片段。我是iOS的新手 – Rishab

+0

哪部分? – jrturton

+0

對於完全保存操作 – Rishab