Reputation: 15
I am having a syntax issues I just cannot figure out. I do not have a strong Swift back ground, so the answer my be easy (I hope.) So, here is the snippet:
public func getLatestDate()-> NSDate? {
var request = NSFetchRequest()
var entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.managedObjectContext)
request.entity = entity
let sortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false)
let sortDescriptors = [sortDescriptor]
request.sortDescriptors = sortDescriptors
var error: NSError? = nil
do {
let results = try self.managedObjectContext.executeFetchRequest(request)
} catch {
fatalError("Failed to fetch employees: \(error)")
}
var date: NSDate?
if results != nil {
let managedObject: NSManagedObject = results![0] as NSManagedObject
date = managedObject.valueForKey("timeStamp") as? NSDate
}
return date
}
The problem is that if results != nil
and the results
on the following line are throwing an error stating:
Use of unresolved identifier 'results'
How do I resolve this issue?
Thank you.
-Matt
Upvotes: 0
Views: 30
Reputation: 1888
in addition to Gavin: this will work cause of the reason, thar Gavin mentioned
do {
let results = try self.managedObjectContext.executeFetchRequest(request)
if results != nil {
let managedObject: NSManagedObject = results![0] as NSManagedObject
date = managedObject.valueForKey("timeStamp") as? NSDate
}
} catch {
fatalError("Failed to fetch employees: \(error)")
}
Upvotes: 0
Reputation: 8200
You're declaring results
here:
do {
let results = try self.managedObjectContext.executeFetchRequest(request)
} catch {
fatalError("Failed to fetch employees: \(error)")
}
So you can see that it's being done within a do-catch
block. That means that where you try to use it is out of the scope where it was defined, so it can't see it at all. By the time you get to if results != nil
, it's already gone out of scope and is gone.
Upvotes: 1