1

i want to save NSDate from XML to coreData. I dont know how to set the Value for NSDate. Can someone give me little help? My Entity attribute is NSDate. Or should it be a String and Save the Date as String??

[Sets setValue:[TBXML textForElement:xmlDate] forKey:@"beginDate"];

Thanks for any response and help,
brush51

2
  • Saving dates as strings is going to leave you in a world of hurt. Leave dates as NSDates and transform them into their readable formats, whether as NSStrings, NSCalendar dates, date components. You get so much for free just by leaving a date as a date.
    – Abizern
    Sep 7, 2011 at 12:15
  • Thanks alot for your Help. i have combined the code, to get it in one line(just to setValue) : [Sets setValue:[myXMLdateReader dateFromString:[TBXML textForElement:xmlDate]] forKey:@"beginDate"];
    – brush51
    Sep 7, 2011 at 14:09

2 Answers 2

6

Whether you are intentionally obfuscating or not, you don't say it, so I'm going to guess that:

  • [TBXML textForElement:xmlDate] returns an NSString
  • beginDate is a Date property of entity Sets

In which case your code is obviously incorrect: you must pass an instance of NSDate to setValue:forKey:. Your code would look like:

NSDateFormatter *myXMLdateReader = [[NSDateFormatter alloc] init];
[myXMLdateReader setDateFormat:@"yyyy-MM-dd"]; // for example
NSDate *itsDate = [myXMLdateReader dateFromString:[TBXML textForElement:xmlDate]];
[myXMLdateReader release];
[Sets setValue:itsDate forKey:@"beginDate"];
3

It is no problem to add NSDate to CoreData. All you need to do is to convert NSString from XML file to NSDate object. For converting NSString <-> NSDate you can use NSDateFormatter class. In example below you can see how I do this:

NSDateFormatter *parseFormatter = [[[NSDateFormatter alloc] init] autorelease];
[parseFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"US"] autorelease]];
[parseFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];
NSString *dateString = @"Mon, 02 May 2011 21:12:56 +0000";
NSDate *dateToAdd = [parser.parseFormatter dateFromString:dateString];

You can set needful date format and use this code in your project.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.