我试图检查该项目是否退出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!
答案 0 :(得分:4)
使用NSPredicate来过滤coredata中的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")
}
答案 1 :(得分:4)
如果任何机构正在寻找swift 3解决方案:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="topnavbar" class="topNavBar">
<!--Logo and some contents here -->
</div>
答案 2 :(得分:0)
func checkIfItemExist(id: String) -> Bool {
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Products")
fetchRequest.fetchLimit = 1
fetchRequest.predicate = NSPredicate(format: "productId == %@" ,id)
do {
let count = try DatabaseHelper.context!.count(for: fetchRequest)
if count > 0 {
return true
}else {
return false
}
}catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
return false
}
}