Storing date value into Core Data in Objective C - objective-c

Can anyone tell me please how to save only date value to Core Data using objective C? I am using UIDatePicker. I searched a lot, but couldn't find any. Can you be more specific because i am newbie. Thanks
Here is my code for adding data to core data database. But instead of formatting dates into string I would like to save as a NSdate. I am creating an calendar app that stores events into CoreData. Is there any help?
- (IBAction)btnSave:(UIBarButtonItem *)sender {
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [delegate managedObjectContext];
NSManagedObject *dataRecord = [NSEntityDescription insertNewObjectForEntityForName:#"Scheduler" inManagedObjectContext:context];
[dataRecord setValue:self.txtBxCustomerName.text forKey:#"customerName"];
[dataRecord setValue: [self date] forKey:#"date"];
[dataRecord setValue:[self begin] forKey:#"startTime"];
[dataRecord setValue:[self end] forKey:#"endTime"];
NSError *error;
if (![context save:&error]) {
NSLog(#"Error! %#", error);
}
[self dismissViewControllerAnimated:true completion:nil];
}
- (IBAction)datePicker:(id)sender {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM-dd-yyyy"];
NSString *string = [dateFormat stringFromDate:self.dateTime.date];
date = string;
}
- (IBAction)startTimePicker:(id)sender {
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"HH:mm"];
NSString *str = [timeFormat stringFromDate:self.startTime.date];
begin = str;
}
- (IBAction)endTimePicker:(id)sender {
NSDateFormatter *endTimeFormatt = [[NSDateFormatter alloc] init];
[endTimeFormatt setDateFormat:#"HH:mm"];
NSString *sting = [endTimeFormatt stringFromDate:self.endTime.date];
end = sting;
}

Get the date from the picker with
NSDate *chosenDate = myDatePicker.date;
and then set it to the desired attributed (in the example startDate) of your model, which should be define in Core Data as type Date
myCoreDataObject.startDate = chosenDate;
or even shorter
myCoreDataObject.startDate = myDatePicker.date;

Related

Property not found on object of type error

I am trying to access a class method from another class but I am getting error. I have a class 'Constants' in which I have written a class method 'changeDateFormat' and accessing it from some viewController.
Here is my code.
Constants.h
#interface Constants : NSObject
+(NSString *)changeDateFormat:(NSString *)currentDate;
#end
Constans.m
#implementation Constants
+(NSString *)changeDateFormat: (NSString *) currentDate
{
NSString *convertedDate = #"";
#try
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM dd yyyy"];
NSDate *date = [dateFormatter dateFromString:currentDate];
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
[dateFormatter1 setDateFormat:#"yyyy-mm-dd"];
convertedDate = [dateFormatter1 stringFromDate:date];
}
#catch(NSException *e)
{
NSLog(#"%# %#", e.name, e.reason);
}
return convertedDate;
}
#end
I am trying to access the above method like Constants.changeDateFormat:#"Mar 11 2018" but I am getting error - Property not found on object of type.
You are sending the changeDateFormat: method. You don't use a . for that. This is the correct syntax:
NSString *output = [Constants changeDateFormat:input];

Working with Date and Time separately using NSDatePickerView on Xcode

I have a part of app that set date and time of an appointment. For this, I have two NSDatePickerView. The first one I set to NSDatePickerModeDate, while the other one to NSDatePickerModeTime. But actually they should be referring to a same NSDate object inside a NSMutableDictionary entry. I know about NSDatePickerModeDateTime, but I need the date and time to be picked separatedly.
I know how to set up the NSDatePickerView to show and hide and event control and such, but at the event control UIControlEventValueChanged fire for NSDatePickerView, I'm confused on how to code the change for this, and also how to initialise the pickers (datePicker.date = today, timePicker.date = "9:00 AM")
#interface MyViewController () {
NSMutableDictionary *data;
}
#end
#implementation MyViewController
#synthesize datePicker, timePicker;
- (void) viewDidLoad {
[super viewDidLoad];
data = [[NSMutableDictionary alloc] init];
[data setObject:[NSDate date] forKey:#"date"];
datePicker.datePickerMode = UIDatePickerModeDate;
timePicker.datePickerMode = UIDatePickerModeTime;
[datePicker addTarget:self action:#selector(changeDate:) forControlEvents:UIControlEventValueChanged];
[timePicker addTarget:self action:#selector(changeTime:) forControlEvents:UIControlEventValueChanged];
datePicker.date = data[#"date"]; //????
timePicker.date = data[#"date"]; //????
}
- (IBAction) changeDate:(id)sender {
UIDatePickerView *dp = (UIDatePickerView *)sender;
[data setObject:dp.date forKey:#"date"]; //????
}
- (IBAction) changeTime:(id)sender {
UIDatePickerView *tp = (UIDatePickerView *)sender;
[data setObject:tp.date forKey:#"date"]; //????
}
The part that I don't know how to code it is denoted by //????. I've read about NSDateFormatter, NSCalendar, and some kind of date components on some answers, but that was actually making me more confused as it also throws strings and structs into the mix, what to use to do what and when. Please help.
You can set both date pickers to the same date and time. The unused part is there but it isn't displayed and can't be changed. When the user changes the value of one date picker you have to set the other date picker to the same value.
- (IBAction)changeDate:(id)sender {
NSDatePicker *dp = (NSDatePicker *)sender;
[data setObject:dp.dateValue forKey:#"date"];
self.timePicker.dateValue = dp.dateValue;
}
- (IBAction)changeTime:(id)sender {
NSDatePicker *tp = (NSDatePicker *)sender;
[data setObject:tp.dateValue forKey:#"date"];
self.datePicker.dateValue = tp.dateValue;
}
u can try this
///Convert Full date to only date
- (IBAction) changeDate:(UIDatePickerView *)sender {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM/dd/yyyy"];
NSString *dateStr = [dateFormatter stringFromDate:[sender date]];
[data setObject:dateStr forKey:#"date"];
}
///convert Date to only time format
- (IBAction) changeTime:(UIDatePickerView *)sender {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm a"];
NSString *dateStr = [dateFormatter stringFromDate:[sender date]];
[data setObject:dateStr forKey:#"Time"];
}

NSMutableDictionary losing object

I'm trying to store arrays of objects in an Mutable Dictionary, but it seems like the dictionary is losing some of my arrays (or maybe the arrays are losing the data?).
Anyways, here's where I'm at:
- (NSDictionary *)getTicketsByDay:(NSArray *)tickets {
// take an array of tickets and return a dictionary with dates (given by
// NSDateFormatterShortStyle) as keys and arrays of tickets as the values
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterShortStyle];
// get NSDate object without time (only month, day, year)
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSMutableDictionary *datesDict = [[NSMutableDictionary alloc] init];
for (Ticket *ticket in tickets) {
NSDateComponents *ticketDateNoTimeComponents = [calendar components:flags fromDate:[ticket createdAt]];
NSDate *ticketDateNoTime = [calendar dateFromComponents:ticketDateNoTimeComponents];
NSString *dateString = [formatter stringFromDate:ticketDateNoTime];
NSMutableArray *ticketArray = [datesDict objectForKey:dateString];
NSLog(#"%lu", [ticketArray count]);
if (ticketArray == nil) {
NSLog(#"it's here: %#", dateString);
ticketArray = [[NSMutableArray alloc] init];
}
[ticketArray addObject:ticket];
NSLog(#"%lu", [ticketArray count]);
[datesDict setObject:ticketArray forKey:dateString];
}
return datesDict;
}
But then on the console, at random places (although the same places every time), I get something like
41
41
42
0
it's here: 6/29/12
1
even though the key for the previous objects was also "6/29/12". I've also had it print all the keys in the dictionary and there is only 1.
So somewhere I'm losing my data. What's going on?
I should also mention that I'm on 10.7.4 and using ARC.
The code looks fine to me (if you include suggestions from #ConradShultz)
Note that you don't need to create the ticketDateNoTime since you're using a date format, it will always generate the short format string even if the date contains a time...
So your code could be simplified to:
- (NSDictionary *)getTicketsByDay:(NSArray *)tickets {
// take an array of tickets and return a dictionary with dates (given by
// NSDateFormatterShortStyle) as keys and arrays of tickets as the values
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterShortStyle];
NSMutableDictionary *datesDict = [[NSMutableDictionary alloc] init];
for (Ticket *ticket in tickets) {
NSString *dateString = [formatter stringFromDate:[ticket createdAt]];
NSMutableArray *ticketArray = [datesDict objectForKey:dateString];
NSLog(#"%lu", [ticketArray count]);
if (ticketArray == nil) {
NSLog(#"it's here: %#", dateString);
ticketArray = [[NSMutableArray alloc] init];
[datesDict setObject:ticketArray forKey:dateString];
}
[ticketArray addObject:ticket];
NSLog(#"%lu", [ticketArray count]);
}
return datesDict;
}
From the looks of it you'll merely leak memory, and your way of replacing the dictionary entry with itself seems unusual (but I think it should work), but what makes you think you are loosing objects? You are printing the size of your array, which is different for different date strings, so maybe you just got a new date string which made it create a new array for that date?
And about the memory leaking/the unusual code: a more traditional way would be
NSMutableArray *ticketArray = [datesDict objectForKey:dateString];
if (ticketArray == nil) {
ticketArray = [[NSMutableArray alloc] init];
[datesDict setObject:ticketArray forKey:dateString];
[ticketArray release];
}
[ticketArray addObject:ticket];

Sorting Table date Objective-C

I have a table with two columns: Date and Name.
I use this code to sorting elements:
-(id)tableView:(NSTableView *)aTableView
objectValueForTableColumn:(NSTableColumn *)aTableColumn
row:(NSInteger)rowIndex {
NSDictionary *itemDictionary = [itemListArray objectAtIndex:rowIndex];
if (aTableColumn == itemName)
return [itemDictionary valueForKey:#"ItemNameBrowser"];
else if (aTableColumn == dateCare)
{
NSDate *date_to_set;
if ([[itemDictionary valueForKey:#"ItemdateCare"] isKindOfClass:[NSString class]])
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setLocale:[NSLocale currentLocale]];
date_to_set = [dateFormatter dateFromString:[itemDictionary valueForKey:#"ItemdateCare"]];
}
else
{
date_to_set = [itemDictionary valueForKey:#"ItemdateCare"];
}
return date_to_set;
}
else
return nil;
}
//sorting table view
-(void)tableView:(NSTableView *)tableView sortDescriptorsDidChange: (NSArray *)oldDescriptors
{
[itemListArray sortUsingDescriptors: [tableView sortDescriptors]];
[tableView reloadData];
}
-(void)addItem {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setLocale:[NSLocale currentLocale]];
//Valori da aggiungere
NSString *newItemNameBrowser = #"Item";
NSString *newItemDateCare = [NSDate date];
NSMutableDictionary *newItem = [NSMutableDictionary dictionary];
[newItem setValue:newItemNameBrowser forKey:#"ItemNameBrowser"];
[newItem setValue:newItemDateCare forKey:#"ItemdateCare"];
[itemListArray addObject:newItem];
[tableList reloadData];
[dateFormatter release];
}
In MainMenu.xib columns are:
Sort Key ItemName
Selector compare:
and
Sort Key ItemDate
Selector compare:
Columns Name is ok.
The problem is sorting date columns because don't reorder the date correctly.
Elements are considered only numbers.
Thanks for help!
I assume you are storing the dates in your itemListArray as string. Don't. Store them as NSDates, then they will appear sorted correctly.
You'll need to attach an NSDateFormatter to the NSTableColumn text field cell to convert them to a string for viewing.

iPhone simple method definition and calling the current date/time

I'm very new to iPhone development, and I'm trying to write a function which will accept one parameter, and return the current date/month and store it in a variable.
But I'm getting a (null) value with NSLog.
Method:
-(NSString *) getNowDateMonth:(NSString *)type {
NSDate *now = [[NSDate alloc] init];
if (type==#"month") {
NSDateFormatter *monthFormat = [[NSDateFormatter alloc] init];
[monthFormat setDateFormat:#"MM"];
NSString *theMonth = [monthFormat stringFromDate:now];
[monthFormat release];
return theMonth;
} else if (type==#"day") {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd"];
NSString *theDate = [dateFormat stringFromDate:now];
//int setDate = theDate;
[dateFormat release];
return theDate;
}
[now release];
return NULL;
}
Calling the function to get value:
NSString *month = [self getNowDateMonth:#"month"];
NSLog(#"%#", month);
Am I going about this the right way?
First of all, compare the strings using [#"month" isEqualToString:type], because two strings containing the same text ("month") may not be equal by the == operator. == checks if they're the same string object, not strings object with the same contents.
Second of all, you're leaking the date when returning the month or day (not releasing now). You should use [NSDate date]; instead of [[NSDate alloc] init].
To sum up, a suggested better version of this method would be:
-(NSString *) getNowDateMonth:(NSString *)type {
NSDate *now = [NSDate date];
if ([#"month" isEqualToString:type]) {
NSDateFormatter *monthFormat = [[NSDateFormatter alloc] init];
[monthFormat setDateFormat:#"MM"];
NSString *theMonth = [monthFormat stringFromDate:now];
[monthFormat release];
return theMonth;
} else if ([#"day" isEqualToString:type]) {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd"];
NSString *theDate = [dateFormat stringFromDate:now];
[dateFormat release];
return theDate;
} else {
return nil;
}
}
Also, there are a few other points that can be taken into consideration to improve this method:
do not use NSString as type; use an enum
do not allocate NSDateFormatter on each call to the method; instead use a static variable in the method
You want to use NSDateComponents to reliably and easily extract unit information i.e. month, day, week etc from an NSDate.
See Date and Time Programming Guide for Cocoa.
Dates are a deceptively complex programing problem so Cocoa has a fully developed set of classes for dealing with them. However, the learning curve is a bit steep.