I'm new to swift and I'm trying to understand parts of it. I've been working on an app where I need to store a date, and I just can't figure it out.
Any input would be great.
Code to store date
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate) var context: NSManagedObjectContext = appDel.managedObjectContext! // Users = Entity in core data var newuser = NSEntityDescription.insertNewObjectForEntityForName("Users",inManagedObjectContext: context) as! NSManagedObject // datetostore = attribute of type date newuser.setValue(NSDate(), forKey: "datetostore") context.save(nil)
Code to get stored data from Core Data
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate) var context: NSManagedObjectContext = appDel.managedObjectContext! var request = NSFetchRequest(entityName: "Users") var results: NSArray = context.executeFetchRequest(request, error: nil)! var end: AnyObject = results var end2 = end as! NSObject var end3 = end2 as! NSDate
Please note: I know the end doesn't really work because that's where I get an error.
First, you should let Xcode generate
NSManagedObject subclasses which will allow stronger typing and more concise code. It will generate a class
User with an attribute
I would recommend to dispense with the silly names such as
datetostore. It's clearly a date, and it is obvious that you are storing it. Thus,
date is quite sufficient.
Finally, from your code it seems that you think the user is the same as the date even though you yourself had just called
setValueForKey to add the date to the user as an attribute. Think about it, and follow what Martin R recommends.
NSManagedObject subclass (not recommended):
let aDate = user.valueForKey("date")
With subclass: fetch your entities with the right type.
let result = context.executeFetchRequest(request, error:nil) as! [User] // check for empty array, then let user = result.first let aDate = user.date