Swift - How to check if CoreData exists

I am trying to check if an item comes out in coredata if not add it to coredata. How can I check?

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!

      

+3


source to share


2 answers


Used by NSPredicate to filter articlIDs in coredata ...



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")
}

      

+4


source


In case any body is looking for a quick solution:



Swift 3 Xcode 8x
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)")
    }
}

      

+3


source







All Articles