核心数据获取数据并查找重复项

时间:2018-09-18 15:52:25

标签: ios swift core-data

我想从Core数据中获取数据并查找重复项,然后仅保存数据,然后没有movieid的重复项。 也许有人可以帮助我..

如何将结果与movieid字符串进行比较?

let request = NSFetchRequest<NSFetchRequestResult>(entityName: "MovieData")
        //request.predicate = NSPredicate(format: "movieid = %@", movieID)
        request.returnsObjectsAsFaults = false
        do {
            let result = try context.fetch(request)
            for data in result as! [NSManagedObject] {
               print(data.value(forKey: "movieid") as! String)
          }

        } catch {

            print("Failed")
        }

3 个答案:

答案 0 :(得分:1)

差不多。应用谓词仅获取具有特定movieID的记录。但是,它假设movieID是一个对象(NSNumber),如果它是标量Int,则必须使用%ld作为占位符。

如果提取返回的是空数组,则不会重复,您可以插入新对象

let request = NSFetchRequest<NSManagedObject>(entityName: "MovieData")
request.predicate = NSPredicate(format: "movieid = %@", movieID)
do {
    let result = try context.fetch(request)
    if result.isEmpty {
        let newMovie = NSEntityDescription.insertNewObject(forEntityName: "MovieData", into: context) as! MovieData
        newMovie.movieid = movieID
        try context.save()
    }      
} catch {
    print(error)
}

答案 1 :(得分:0)

在保存核心数据时,您需要创建谓词,并且在其中需要检查是否已经使用相同的“ movieid”保存了值,然后必须对其进行更新,这样您就不会有重复的数据。请参考该方法并尝试使用该方法将值保存到DB中。这样重复的值将不会保存在数据库中

class func insertupdaterecord (movieID:String, context: NSManagedObjectContext)
{
    let entityDescription = NSEntityDescription.entity(forEntityName: "movie", in: context)
    let pred = NSPredicate(format: "movieid = %@", movieID)

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "movie")
    fetchRequest.entity    = entityDescription
    fetchRequest.predicate = pred

    let result = try! (context.fetch(fetchRequest) as NSArray).lastObject
    let updateInsertInfo : movie

    if result != nil
    {
        updateInsertInfo               = result as! movie
    }
    else
    {
        print("Record not found!")
    }
    do
    {
        try context.save()
    }
    catch let error as NSError
    {
        print("Error while saving \(error) in database.")
    }
}

答案 2 :(得分:0)

movieid值创建一个缓存,以检查重复项并遍历获取的结果,并删除缓存中已有movieid的任何对象,然后在循环完成后保存。

var selection: [String] = []
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "MovieData")

request.returnsObjectsAsFaults = false
do {
    let result = try context.fetch(request)
    for data in result as! [NSManagedObject] {
        guard let movieId = data.value(forKey: "movieid") as? String else {
            context.delete(data) // or however you want to handle this situation
            continue
        }
        if selection.contains(movieId) {
            context.delete(data)
        } else {
            selection.append(movieId)
        }
    }
    try context.save()
} catch {
    print("Failed")
}