迅捷-如何检查CoreData是否存在

ser*_*anc 3 core-data ios swift

我正在尝试检查项目是否在coredata中退出(如果未将其添加到coredata中)。我要如何执行检查?

var authorList = [AuthorList]()

let articleEntity = NSEntityDescription.entityForName("AuthorList", inManagedObjectContext: self.context!)
let newAuthor = AuthorList(entity: articleEntity!, insertIntoManagedObjectContext: self.context!)

   //if authorID is not in coredata then....
     newAuthor.authorName = authorName!
     newAuthor.authorImage = authorImage!
     newAuthor.newspaperName = newspaperName!
     newAuthor.newsPaperImage = newsPaperImage!
     newAuthor.authorID = authorID!
Run Code Online (Sandbox Code Playgroud)

ser*_*anc 5

使用NSPredicate过滤核心数据中的articlID ...

let fetchRequest = NSFetchRequest(entityName: "FavArticles")
let predicate = NSPredicate(format: "articleID == %ld", articleID!)
fetchRequest.predicate = predicate
let fetchResults = self.context!.executeFetchRequest(fetchRequest, error: nil) as? [FavArticles]
if fetchResults!.count > 0 {
  println("already favd")
}
Run Code Online (Sandbox Code Playgroud)


Abd*_*rim 5

如果任何人在寻找快速3解决方案。

  • 迅捷3
  • Xcode 8倍

    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Friends")
        let predicate = NSPredicate(format: "friendName == %@", frd.text)
        request.predicate = predicate
        request.fetchLimit = 1
    
        do{
            let app = UIApplication.shared.delegate as! AppDelegate
            let context = app.managedObjectContext
            let count = try context.count(for: request)
            if(count == 0){
                // no matching object
                print("no present")
            }
            else{
                // at least one matching object exists
                print("one matching item found")
            }
        }
        catch let error as NSError {
            print("Could not fetch \(error), \(error.userInfo)")
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)