I am having an issue with a Swift (2.0) app I am writing in Xcode 7. Basically, I want to save a string to Core Data, and then retrieve it. Sounds really simple but I'm having some issues. The app is a simulated bomb, so I am writing the time it should 'detonate' as a string to Core Data. I then want to retrieve that string and do things with it.
Here is my code to save the string in Core Data:
let dteTime:NSDate = NSDate(timeIntervalSinceNow: 60*60*12) //Generate time 12 hours from now
let formatter:NSDateFormatter = NSDateFormatter()
formatter.timeStyle = NSDateFormatterStyle.LongStyle
formatter.dateStyle = NSDateFormatterStyle.LongStyle
let strStringValue:String = formatter.stringFromDate(dteTime)
print(strStringValue) //Prints 'October 20, 2015 at 5:53:18 AM GMT+11' as expected
let newTime = NSEntityDescription.insertNewObjectForEntityForName("Time", inManagedObjectContext: context)
newTime.setValue(strStringValue, forKey: "dateTimeExplode")
do {
try context.save()
} catch _ {
print("Error saving core data")
}
I have confirmed that calculating the time 12 hours from now is working, and it is formatted into a string correctly.
Below is the code to retrieve the entry from Core Data:
let request = NSFetchRequest(entityName: "Time")
request.returnsObjectsAsFaults = false
var results:[TimeCoreData] = [TimeCoreData]()
results = (try! context.executeFetchRequest(request)) as! [TimeCoreData]
if results.count > 0 { // Data retrieved
var dteTimeExplode:String = String()
for res in results { //CRASHES
dteTimeExplode = res.dteTimeDateExplode
}
}
You'll have to forgive me for any confusion here, but dteTimeExplode
is actually a string, not a date. It was originally an NSDate() but I ran into problems, so to simplify it temporarily, I changed it to a string. There may be a few cases like that throughout the code.
As you can see, I am retrieving the Core Data into a custom object, which is defined below. I have copied the entire swift file.
import UIKit
import CoreData
import Foundation
@objc(TimeCoreData)
class TimeCoreData: NSManagedObject {
@NSManaged var dteTimeDateExplode:String
}
At the moment, the app crashes when it gets to for res in results {
(labelled in the second code chunk above) with the error message
fatal error: NSArray element failed to match the Swift Array Element type
I understand that this error message is being received because Swift is trying to make an array of one type out of data of another type and it is unable to do so, but I don't understand why that is the case. I am saving a string into Core Data, so I should be retrieving a string. My custom object (TimeCoreData
) has only one variable and that is of type string.
Below is a screenshot of my Core Data model:
What am I doing wrong here?