Reputation: 727
im building app where random quote from plist is displaying and you can save it to favorites(core data), I want to check if my random generated quote already exists in core data or no, I just want to change save button if its already saved
Quote.swift:
var quotesPlist: NSArray! = []
override func awakeFromNib() {
loadQuote()
}
func loadQuote(){
let path = NSBundle.mainBundle().pathForResource("quotesList", ofType: "plist")
quotesPlist = NSArray(contentsOfFile: path!)
quoteLbl.text = quotesPlist[Int(randomNumber())] as? String
}
SavedQuote properties:
@NSManaged var quote: String?
@NSManaged var creationDate: NSDate?
@NSManaged var uuid: String?
this is HomeVC:
func createQuoteFromNib() -> QuoteView! {
return NSBundle.mainBundle().loadNibNamed("QuoteView", owner: self, options: nil)[0] as? QuoteView
}
@IBAction func saveACTION(sender: UIBarButtonItem) {
if let label = currentQuote.quoteLbl.text where label != "" {
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
let entity = NSEntityDescription.entityForName("SavedQuotes", inManagedObjectContext: context)!
let quote = SavedQuotes(entity: entity, insertIntoManagedObjectContext: context)
quote.quote = currentQuote.quoteLbl.text
quote.creationDate = NSDate()
quote.uuid = NSUUID().UUIDString
context.insertObject(quote)
do {
try context.save()
} catch let err as NSError {
print(err.debugDescription)
}
}
}
this is my FavoritesVC:
var quotesArray = [SavedQuotes]()
@IBOutlet weak var tableView: UITableView!
func fetchAndSetResults(){
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "SavedQuotes")
let dateSort = NSSortDescriptor(key: "creationDate", ascending: false)
fetchRequest.sortDescriptors = [dateSort]
do {
let results = try context.executeFetchRequest(fetchRequest)
quotesArray = results as! [SavedQuotes]
} catch let err as NSError {
print(err.debugDescription)
}
}
Upvotes: 0
Views: 591
Reputation: 119031
It isn't clear how you're generating this new quote. At minimum you need to use a fetch request to check if the quote exists before you call insertIntoManagedObjectContext
. You can do that as soon as the quote exists and you're configuring the view (with the quote text and the save button).
Your fetch request uses a simple predicate to check for a quote with matching quote
text.
You already have a fetch request to list all the quotes, so all you need to add to that for the check is a predicate with format "quote = %@"
and check the count of the results (which should always be either 0 or 1 (meaning save and don't save respectively).
Upvotes: 2