Maselko
Maselko

Reputation: 4128

How to check whether record exists in Core Data? If yes don't add another. Swift

I have now something like this:

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

I can see actual month "February".

How check whether this month already exists in the database? If there is a month that does not add the next record.

Regards, Mateusz Fraczek

Upvotes: 0

Views: 4500

Answers (1)

kellanburket
kellanburket

Reputation: 12833

Assuming that DateString is a child class of NSManagedObject, you should be able to grab DateString records from Core Data by running something like the following:

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

Upvotes: 1

Related Questions