Core Data: Not saving - core-data

I'm having trouble saving to one variable letsMeet.startTimeLabel. Right after selecting NSLog shows the correct Value, however, after I save to another variable (letsMeet.endTimeLabel), letsMeet.startTimeLabel changes to (NULL). Below is the code:
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
letsMeet = (LetsMeet *) [NSEntityDescription insertNewObjectForEntityForName:#"LetsMeet" inManagedObjectContext:managedObjectContext];
switch (actionSheet.tag)
{
case 1:
{
if (buttonIndex == 0)
{
UIDatePicker *startDatePicker = (UIDatePicker *)[actionSheet viewWithTag:kDatePickerTag1];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd"];
NSDate *selectedDate = [startDatePicker date];
NSDateFormatter *dayFormatter = [[NSDateFormatter alloc] init];
[dayFormatter setDateFormat:#"EEEE"];
NSDate *selectedDay= [startDatePicker date];
NSDateFormatter *monthFormatter = [[NSDateFormatter alloc] init];
[monthFormatter setDateFormat:#"MMMM"];
NSDate *selectedMonth = [startDatePicker date];
NSString *date = [[NSString alloc] initWithFormat:#"%#", [dateFormatter stringFromDate:selectedDate]];
DateLabel.text = date;
[letsMeet setDateLabel:date];
NSString *month = [[NSString alloc] initWithFormat:#"%#", [dayFormatter stringFromDate:selectedMonth]];
MonthLabel.text = month;
[letsMeet setMonthLabel:month];
NSString *day = [[NSString alloc] initWithFormat:#"%#", [monthFormatter stringFromDate:selectedDay]];
DayLabel.text = day;
[letsMeet setDateLabel:day];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat: #"h:mm a"];
NSDate *selectedStartTime = [startDatePicker date];
NSString *startTime = [[NSString alloc] initWithFormat:#"%#", [timeFormatter stringFromDate:selectedStartTime]];
StartTimeLabel.text = startTime;
[letsMeet setStartTimeLabel:startTime];
NSError *error = nil;
if (![managedObjectContext save:&error]){
NSLog(#"Error Saving");
}
}
NSLog (#"This is the StartTime after selecting %#", letsMeet.startTimeLabel);
}
break;
case 2:
{
if (buttonIndex == 0)
{
UIDatePicker *endTimePicker = (UIDatePicker *)[actionSheet viewWithTag:kDatePickerTag2];
NSDateFormatter *endTimeFormatter = [[NSDateFormatter alloc] init];
[endTimeFormatter setDateFormat: #"h:mm a"];
NSDate *endSelectedTime = [endTimePicker date];
NSString *endTime = [[NSString alloc] initWithFormat:#"%#", [endTimeFormatter stringFromDate:endSelectedTime]];
EndTimeLabel.text = endTime;
[letsMeet setEndTimeLabel:endTime];
NSLog (#"This is the EndTime %#", letsMeet.endTimeLabel);
NSLog (#"This is the StartTime after selecting BOTH %#", letsMeet.startTimeLabel);
}
else if (buttonIndex == 1)
{
EndTimeLabel.text = #"Whenever";
[letsMeet setEndTimeLabel:EndTimeLabel.text];
}
NSError *error = nil;
if (![managedObjectContext save:&error]) {
}
}break;
// Handle the error.
}
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
UIViewController *destinationViewController = segue.destinationViewController;
NSLog (#"Prepare For Segue StartTime %#", letsMeet.startTimeLabel);
NSLog (#"Prepare For Segue EndTime%#", letsMeet.endTimeLabel);
}
Here is the log:
2013-02-20 21:38:24.253 AppointmentTime[3129:c07] This is the StartTime after selecting 9:30 AM
2013-02-20 21:38:32.325 AppointmentTime[3129:c07] This is the EndTime 12:15 PM
2013-02-20 21:38:32.325 AppointmentTime[3129:c07] This is the StartTime after Selecting BOTH (null)
2013-02-20 21:38:34.069 AppointmentTime[3129:c07] Prepare For Segue StartTime (null)
2013-02-20 21:38:34.069 AppointmentTime[3129:c07] Prepare For Segue EndTime12:15 PM
Q: Why would letsMeet.startTimeLabel show up correct the first time and after selecting EndTime, it changes to NULL. Please note EndTime continues to show the correct Value all the way up to prepareForSegue. Weird!

According to your logs and code , you are entering the switch block twice. Which means you are entering the actionSheet:clickedButtonAtIndex: method twice. So each time you enter the method
letsMeet = (LetsMeet *) [NSEntityDescription insertNewObjectForEntityForName:#"LetsMeet" inManagedObjectContext:managedObjectContext];
statement is executed twice, in turn creating two objects. You can see this by doing a fetch from the store.
So you are checking for properties in two different objects and hence the null.
If you are using just one managed object, you can probably add a check for nil for the object before executing insertNewObjectForEntityForName:inManagedObjectContext:. This will make sure you are using the same object.
If you are using more than one object at the same time use the object id or some unique key to identify your object and manipulate it.
Edit:
You can check for nil with the following code:
if(letsMeet==Nil){
letsMeet = (LetsMeet *) [NSEntityDescription insertNewObjectForEntityForName:#"LetsMeet" inManagedObjectContext:managedObjectContext];
}
This will work only, if the object you are calling the actionSheet:clickedButtonAtIndex: method is always in memory. But since you are persisting you might want to fetch the object from the store and then check for no. of objects.
NSError *error;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"LetsMeet" inManagedObjectContext:managedObjectContext]];
NSArray *objectArray = [managedObjectContext executeFetchRequest:request error:&error]
if(objectArray.count==0){
letsMeet = (LetsMeet *) [NSEntityDescription insertNewObjectForEntityForName:#"LetsMeet" inManagedObjectContext:managedObjectContext];
}else{
letsMeet = (LetsMeet *)[objectArray objectAtIndex:0];
}
Note: If you need to persist only a couple of variables, core-data might be an overkill. Use NSUserDefaults instead and keep it simple.

Related

Fetching Sorted Array based on NSDate from Core Data Entity in iOS9 using Objective C

I am using core data for storing alarm details (AlarmDate is stored as Date type), while fetching all alarms i have used NSSortDescripotor as
NSManagedObjectContext *managedObjectContext = [(AppDelegate *)[UIApplication sharedApplication].delegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Alarm"];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"AlarmDate"
ascending:YES];
NSArray *sortDescriptors = #[sortDescriptor];
[fetchRequest setSortDescriptors:sortDescriptors];
NSArray *arrayForAllAlarms = [managedObjectContext executeFetchRequest:fetchRequest error:nil];
for above it is returning the alarms in sorted order, but i need it should also consider the AM and PM while sorting
Example:
if alarms date are added like:
11.00 pm,
01.30 am and
10.00 pm
it should return:
01.30 am
10.00 pm and
11.00 pm
Thank you!
Find Solution, Written custom sorting for existing fetched array as following:
NSArray *arrayForAllAlarmsSorted = [arrayForAllAlarms sortedArrayUsingComparator:
^(Alarm *alarmObject1, Alarm *alarmObject2) {
NSDate *dateForAlarm1 = [NSDate date:alarmObject1.alarmDateTime withFormat:#"hh:mm a"];
NSDate *dateForAlarm2 = [NSDate date:alarmObject2.alarmDateTime withFormat:#"hh:mm a"];
return [dateForAlarm1 compare:dateForAlarm2];
}];
And the NSDate Category function written as:
+(NSDate *)date:(NSDate *)date withFormat:(NSString *)format {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
dateFormatter.dateFormat = format;
NSDate *newDate = [dateFormatter dateFromString:[dateFormatter stringFromDate:date]];
return newDate;
}

core data simple fetch request template

I have a small core data base "Guests" and I am trying to get the results from a fetch request template called FetchRequestA, I made a button to trigger in the console the results from the request but I keep on getting a null answer, the request is set to display all guestlastnames that contain a d ? here is the code that i am using :
- (IBAction)fetchA:(id)sender {
NSFetchRequest *request2 = [[[self managedObjectModel] fetchRequestTemplateForName:#"FetchRequestA"] copy];
NSSortDescriptor *sort = [[NSSortDescriptor alloc]initWithKey:#"guestlastname" ascending:YES];
[request2 setSortDescriptors:[NSArray arrayWithObject:sort]];
NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:sort, nil];
[request2 setSortDescriptors:sortDescriptors];
NSError *error = nil;
NSArray *fetchedObjects = [[self managedObjectContext] executeFetchRequest:request2 error:&error];
if (fetchedObjects == nil) {
NSLog(#"problem %#", error);
}
for (Guests *guestlastname in fetchedObjects) {
NSLog(#"Fetched Object = %#", guestlastname.guestlastname);
}
}
Am I missing a method ? have perused around but to no avail, thanks in advance.
Here is solution :
(IBAction)gettemplatebutton:(id)sender {
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObjectModel* model = [[context persistentStoreCoordinator] managedObjectModel];
NSDictionary* dict = [[NSDictionary alloc]initWithObjectsAndKeys: self.fetchedObjects, #"guestlastname",nil];
NSFetchRequest* request2 = [model fetchRequestFromTemplateWithName:#"FetchRequestA" substitutionVariables: dict];
NSError* error = nil;
NSArray *Guests2 = [context executeFetchRequest:request2 error:&error];
NSString *g3 = #"";
for(NSManagedObject *guestlastname in Guests2)
{
g3 = [g3 stringByAppendingString:[NSString stringWithFormat:#"%#\n", [guestlastname valueForKey:#"guestlastname"]]];
}
self.displaytemplateLabel.text = g3;
[_displaytemplateLabel setNumberOfLines:0];
for (NSManagedObject *guestlastname in Guests2)
{
{
NSLog(#"%#", [guestlastname valueForKey:#"guestlastname"]);
}
}
}
and added #property (nonatomic, retain) NSArray *fetchedObjects; in header file.

Failing to add NSDate into NSDictionary

I am trying to addd my nsdate into nsdictionary.CAn anyone tell me how to add it?
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
//if(conditionCount ==0){
if( [#"forecast_information" isEqualToString:elementName] ) {
//conditionDate = get date
NSDate *now=[NSDate date];
isParsingInformation=YES;
NSArray *array=[NSArray arrayWithObject:now];
NSLog(#" the time is %#",array);
[forecastConditions addObject:[NSMutableDictionary dictionary]];
}
else if([#"forecast_date" isEqualToString:elementName])
{
if(!forecast_information)
forecast_information=[[NSMutableArray alloc]init];
}
else if(isParsingInformation){
NSMutableDictionary *field=[forecastConditions lastObject];
[field setObject:[attributeDict objectForKey:#"data"] forKey:elementName];
}
i dnt know..see what I actually want to do is I am getting my google weather api in an nsdictionary named fields..I want to add my NSDate from the system at the first index of nsdictionary..I NSdictionary I couple of data,I want to add my nSdate at the first index..I am not able to do it.
I am trying to increment by date by each loop...how to do it?
i think it is date not data
[field setObject:[attributeDict objectForKey:#"date"] forKey:elementName];
updated code
NSMutableDictionary *dic=[[NSMutableDictionary alloc] init];//creation
[dic setObject:[NSDate date] forKey:#"Today"];//added
NSLog(#"dic is : %# \n\n",dic);
NSDate *now = [NSDate date];
int daysToAdd = 50; // or 60 :-)
NSDate *newDate1 = [now addTimeInterval:60*60*24*daysToAdd];
NSLog(#"Quick: %#", newDate1);
OR
NSDate *now = [NSDate date];
int daysToAdd = 50; // or 60 :-)
// set up date components
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setDay:daysToAdd];
// create a calendar
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *newDate2 = [gregorian dateByAddingComponents:components toDate:now options:0];
NSLog(#"Clean: %#", newDate2);

Printing Core Data

I'm working on a program and I have created a fetch request to grab the data that I need to print. I'm able to log information like this:
2010-10-03 16:57:10.362 lzshow7.2[2537:10b] <NSManagedObject: 0x2ca120> (entity: Song; id: 0x2afcb0 <x-coredata://CF5A85CE-BE0F-4ADC-979A-7F4214A8FB19/Song/p9> ; data: {
cueName = Freedom;
cueNo = 014;
cueNotes = nil;
songToInstrument = "<relationship fault: 0x2b1800 'songToInstrument'>";
})
How do I seperate the properties like cueName, cueNo, cueNotes out to be printed?
Here is the fetch request:
//Managed object context???
NSLog(#"setting Managed object stuff");
NSManagedObjectContext *context=[[[NSDocumentController sharedDocumentController] currentDocument] managedObjectContext];
NSLog(#"Second line of Managed object stuff");
//fetch request:
NSLog(#"Starting to fetch:");
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Song" inManagedObjectContext:context];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"cueNo" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
NSError *error;
NSMutableArray *mutableFetchResults = [[context executeFetchRequest:request error:&error] mutableCopy];
for (id obj in mutableFetchResults)
NSLog(#"%#", obj);
NSLog(#"finished looping");
//Error handling
if (mutableFetchResults == nil) {
// Handle the error.
}
//[self setEventsArray:mutableFetchResults];
[mutableFetchResults release];
[request release];
}
Any help would be greatly appreciated.
Thank you,
Loren
You use basically the opposite of how you stored the values in your managedObject
NSString *name = [song valueForKey:#"cueName"];
NSNumber *number = [song valueForKey:#"cueNo"];
NSString *notes = [song valueForKey:#"cueNotes"];
...
NSLog(#"%# %# %#", name, number, notes);
if you've created a custom Class of your entity you could add this method:
- (NSString *)description {
NSString *name = [song valueForKey:#"cueName"];
NSNumber *number = [song valueForKey:#"cueNo"];
NSString *notes = [song valueForKey:#"cueNotes"];
...
NSString *returnString = [NSString stringWithFormat:#"%# %# %#", name, number, notes];
return returnString;
}
With this method you can just use NSLog(#"%#", object); to get a nice formatted output

Core Data complex query

I have model that have field date. I need to fetch all count of records for all day of year or if no record for this day presented fetch as 0. Now i fetch all record for year and make it by hands. Can I do it using core data queries?
Typically in Core Data it is much faster to do all the fetching you will need to do up front rather than breaking it up into multiple fetches.
I tried to count records by day of the year in two ways:
Fetch all the records for a year. Find distinct dates for those records. Loop over the dates and count the records.
Loop over each day in the year. Perform a count-only fetch for the records with that date.
With a small database (48 records), the first approach was about 90 times faster. I imagine the performance of the first approach would get worse as more records are added and the second approach would stay about the same.
Here is the code:
- (void)doFullLoadTestWithYear:(int)year {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Record" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
[comps setDay:1];
[comps setMonth:1];
[comps setYear:year];
NSDate *start = [gregorian dateFromComponents:comps];
[comps setDay:31];
[comps setMonth:12];
NSDate *end = [gregorian dateFromComponents:comps];
NSPredicate *yearPred = [NSPredicate predicateWithFormat:#"date >= %# && date <= %#",start,end];
[fetchRequest setPredicate:yearPred];
NSError *error = nil;
NSArray *array = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];
if (error) {
NSLog(#"Error during fetch: %#",[error localizedDescription]);
abort();
}
int dateCount = 0, recordCount = 0;
NSArray *dates = [array valueForKeyPath:#"#distinctUnionOfObjects.date"];
for (NSDate *date in dates) {
NSPredicate *pred = [NSPredicate predicateWithFormat:#"date == %#",date];
NSArray *records = [array filteredArrayUsingPredicate:pred];
dateCount++;
recordCount += [records count];
NSLog(#"%d record(s) with date %#",[records count],date);
}
NSLog(#"Record count for year is %d",recordCount);
NSLog(#"Distinct dates count is %d",dateCount);
}
- (void)doSeparateTestWithYear:(int)year {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Record" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
[comps setDay:1];
[comps setMonth:1];
[comps setYear:year];
NSDate *start = [gregorian dateFromComponents:comps];
[comps setYear:year+1];
NSDate *end = [gregorian dateFromComponents:comps];
NSDateComponents *oneDay = [[[NSDateComponents alloc] init] autorelease];
[oneDay setDay:1];
int dateCount = 0, recordCount = 0;
NSDate *date = start;
while (![date isEqual:end]) {
NSPredicate *dayPred = [NSPredicate predicateWithFormat:#"date == %#",date];
[fetchRequest setPredicate:dayPred];
NSError *error = nil;
int count = [self.managedObjectContext countForFetchRequest:fetchRequest error:&error];
if (error) {
NSLog(#"Error during fetch: %#",[error localizedDescription]);
abort();
}
if (count > 0) {
NSLog(#"%d record(s) with date %#",count,date);
dateCount++;
recordCount += count;
}
date = [gregorian dateByAddingComponents:oneDay toDate:date options:0];
}
NSLog(#"Record count for year is %d",recordCount);
NSLog(#"Distinct dates count is %d",dateCount);
[fetchRequest release];
}

Resources