我正在构建应用程序,其中plist的随机引用正在显示,您可以将其保存到收藏夹(核心数据),我想检查我的随机生成的引用是否已经存在于核心数据中或者没有,我只想更改保存按钮如果它已经保存了
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属性:
@NSManaged var quote: String?
@NSManaged var creationDate: NSDate?
@NSManaged var uuid: String?
这是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)
}
}
}
这是我的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)
}
}
答案 0 :(得分:1)
您无法清楚如何生成此新报价。在调用insertIntoManagedObjectContext
之前,您至少需要使用获取请求来检查引用是否存在。只要报价存在并且您正在配置视图(使用报价文本和保存按钮),您就可以这样做。
您的提取请求使用简单谓词来检查匹配quote
文本的报价。
您已经有一个获取请求来列出所有引号,因此您需要添加的所有引号都是格式为"quote = %@"
的谓词并检查结果的计数(应始终为0)或1(意思是保存并不分别保存)。