从核心数据中的实体中删除记录

时间:2017-06-06 05:56:11

标签: ios swift core-data swift3

我正在使用swift 3.0中的一个项目,其中我有一个核心数据模块,其中包含一个名为“PlayListDetails”的实体。这包含两个子元素名称playlistName和trackID。因此,每个播放列表名称都有一个trackID interline。我的要求是在传递indexPath.row时删除特定元组。虽然我执行方法后已经实现了一个方法但它给了我一个例外,说“致命错误:索引超出范围”。我的方法如下所示我保存数据和我用来删除数据的方法。

保存

 public static func savePlaylistDetails(audio:[(title:String,healerName:String,trackUrl:String, trackID:String, imageUrl: String)] = [], playListName: String) {

        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext
        let newPlaylist = NSEntityDescription.insertNewObject(forEntityName: PlayList_DETAILS_ENTITY, into: context)

        let track = audio.map{$0.trackID}
        print("Track",track)

        let trackId = track[0]

        print("ID is :",trackId)
        newPlaylist.setValue(playListName, forKey:"playlistName")
        newPlaylist.setValue(trackId, forKey:"trackID")

        do{
            try context.save();
            print("Saved.....")
        }
        catch{
            print("There was an error")
        }
    }

删除//这是我得到异常的地方,我将选定的rowIndex传递给函数

func deleteCoreData(rowIndex: Int) {
    let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    var playList = [PlayListDetails] ()
    managedContext.delete(playList[rowIndex]) // this is where the exception throws


    do {
         try managedContext.save()

    }catch{
        print("fail")
    }

}

我错过了什么?

2 个答案:

答案 0 :(得分:1)

如果你试图删除具有特定索引的项目,我已经提供了在索引处删除项目的解决方案(这可能会导致数组超出绑定异常),但我建议使用谓词,假设可能是id,名称您愿意删除的项目。

我正在根据您的问题提供感知解决方案, 您可以使用从DB获取实体的过程并删除要删除的特定项目。

请设法添加以下代码,如果要删除某些特定项目,请不要忘记使用谓词

 func deleteCoreData(rowIndex: Int) {

    let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    do{
        //1. Create Request
        let request: NSFetchRequest<PlayListDetails> = PlayListDetails.fetchRequest()

        //Predicate is optional as per need
        //let predicate = NSPredicate(format: "playlistId = %@", id)
        //request.predicate = predicate

        //2. Result object
        let results = try managedObjectcontext.fetch(request as! NSFetchRequest<NSFetchRequestResult>)

        guard results.count > 0 else {
            print("No tems available handle error")
            return
        }

        for i in 0...results.count-1 {

            if i == rowIndex {
                let theItem = results[index] as NSManagedObject
                managedObjectcontext.delete(item)
            }
        }
         /*
        for item in results as! [NSManagedObject]{
            print(item)
            //hit delete for item you want
            managedObjectcontext.delete(item)
        } */

        do {
            try managedObjectcontext.save() // <- remember to put this :)

        } catch {
            // Do something... fatalerror
            print("handle error")
            return
        }

    } catch{
        print(error)
        print("handle error")
        return

    }
    print("handle error")

}

<强>更新

&#34;这是我想要执行的查询先生..从PlayListDetails中删除所有,其中trackId = 123和playlistName = demo我将如何在上面的代码中实现这一点&#34;

使用谓词

//use predicate for single predicate and compound for multiple predicate 
//Predicate is optional as per need
let predicate = NSPredicate(format: "trackId = %@", id)
let predicate2 = NSPredicate(format: "name = %@", "some name")

//let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, predicate2])

    request.predicate = predicate
删除部分

使用

for item in results as! [NSManagedObject]{
                print(item)
                //hit delete for item you want
                managedObjectcontext.delete(item)
            } 

答案 1 :(得分:1)

从核心数据快速4中删除实体中的记录

let appDelegate = UIApplication.shared.delegate as! AppDelegate

let context = appDelegate.persistentContainer.viewContext

let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")

request.predicate = NSPredicate(format: "age = %@ AND username = %@", self.aryOfUsersModel[indexPath.row].value(forKey: "age") as! String,self.aryOfUsersModel[indexPath.row].value(forKey: "username") as! String)

do {
      let result = try context.fetch(request)

      print("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-")
      print("total record aryOfUsersModel \(self.aryOfUsersModel.count)")
      print("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-")

      for data in result as! [NSManagedObject]
      {
         context.delete(data)
      }
      // fetch all record here after deleting
   }

也更新管理上下文

try context.save()