Swift - 如何从UITableView获取对象id并根据对象id删除对象?

时间:2015-02-09 11:34:56

标签: ios uitableview swift core-data

现在我遇到了这个问题,我不知道如何在用户从中选择后从UITableView中获取对象id,而在另一个视图控制器中,我想根据我之前从中获取的对象id删除该对象之一。

的UITableView

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        /* grab object id here and pass to NSUserDefault*/

        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

        let deleteViewController = storyBoard.instantiateViewControllerWithIdentifier("accessView") as DeleteViewController
        self.presentViewController(deleteViewController, animated:true, completion:nil)

    }

DeleteViewController

/* Delete object happen here*/

请指教。谢谢。

2 个答案:

答案 0 :(得分:1)

您可以在DeleteViewController中设置属性,并在初始化视图控制器时将值传递给它。

class DeleteViewController {
  var objectId: Int?
}

// Previous view controller
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

  // Grab your object from the data source
  let object = dataSource[indexPath.row]

  let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

  let deleteViewController = storyBoard.instantiateViewControllerWithIdentifier("accessView") as DeleteViewController

  // Pass the Id
  deleteViewController.objectId = object.objectId
  self.presentViewController(deleteViewController, animated:true, completion:nil)


}

答案 1 :(得分:0)

我已经找到了答案。

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        let data: NSManagedObject = myList[indexPath.row] as NSManagedObject

        let objectId = data.valueForKeyPath("objectId") as? String
        NSUserDefaults.standardUserDefaults().setObject(objectId, forKey: "objectId")

        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
        let deleteViewController = storyBoard.instantiateViewControllerWithIdentifier("accessView") as DeleteViewController
        self.presentViewController(deleteViewController, animated:true, completion:nil)

    }