如何检查Core Data中是否存在记录?如果是,请不要添加另一个。迅速

时间:2015-02-05 14:23:52

标签: swift core-data

我现在有这样的事情:

     func addMonth() {
    let appDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    var managedObjectContext = appDelegate.managedObjectContext
    let entityDescription = NSEntityDescription.entityForName("DateString", inManagedObjectContext: managedObjectContext!)

    let data = DateString(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext!)

    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
    var dateString = datePicker.date.description
    var date = dateFormatter.dateFromString(dateString)
    dateFormatter.dateFormat = "MMMM"

    var dateString2 = dateFormatter.stringFromDate(date!)
    println(dateString2)
    data.date = dateString2


    //appDelegate.saveContext()
}

我可以看到实际的月份"二月"。

如何检查数据库中本月是否已存在?如果有一个月没有添加下一条记录。

此致 Mateusz Fraczek

1 个答案:

答案 0 :(得分:1)

假设DateString是NSManagedObject的子类,您应该能够通过运行以下内容从Core Data中获取DateString记录:

let entity = "DateString" 
var request = NSFetchRequest(entityName: entity)
var error: NSError?
if let entities = managedObjectContext.executeFetchRequest(
    request,
    error: &error
) as? [NSManagedObject] {
    for entity in entities {
        if let dateString = entity as DateString {
            ...do whatever tests you need with the new DateString instance
        } 
    }
}