Trouble with CoreData and finding date - objective-c

I have a simple model, that represents Days meals and training sessions. I am having an issue with getting the Day from CoreData. I get the following error.
2011-11-14 11:41:44.999 CalorificCounter[21002:fb03] -[__NSCFString timeIntervalSinceReferenceDate]: unrecognized selector sent to instance 0x6a6d1a0
2011-11-14 11:41:45.001 CalorificCounter[21002:fb03] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString timeIntervalSinceReferenceDate]: unrecognized selector sent to instance 0x6a6d1a0'
Code
-(Day *)getDayForDate:(NSDate *)date
{
Day *day;
date = [self dateAtStartOfDay:date];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Day"
inManagedObjectContext:[self managedObjectContext]];
//Find the object that matches the given date from a predicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"date == \"%#\"",date];
[request setEntity:entity];
[request setPredicate:predicate];
//Try to fetch
NSError *error;
NSArray *result = [[self managedObjectContext] executeFetchRequest:request
error:&error ] ;
The error occurs on the execution of the fetch request. I have traced execution and everything seems to be the correct type (at least I am never passing a string around). Thanks in advance.
UPDATE Dont put the predicated date in quotes
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"date == %#",date];

This issue occur when you have assign a String to the date object. Check the date value and return a NSDate object

Related

Core Data and NSPredicate

I'm looking for a way to use NSPredicate to set a "beginswith [cp]" condition to fetch objects. In the data model there is an one entity which contains 4 basic attributes. Name of first attribute is cityName. The goal is to find records for which cityName begins with given character, but I'm not sure how to format the predicate.
This is part of my code for this
NSString * lastCharacter = [userCity substringFromIndex:[userCity length] -1];
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
[appDelegate managedObjectContext];
NSEntityDescription *entityDesc =
[NSEntityDescription entityForName:#"Cities"
inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(cityName = beginswith [cp] %# )", lastCharacter];
[request setPredicate:pred];
but for this code I get following error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "(cityName = beginswith [cp] %# )"'
The problem is that the beginswith is an operator, so = beginswith is one too much. The brackets in your predicate are also not necessary. Thus:
[NSPredicate predicateWithFormat:#"cityName beginswith[cd] %#", lastCharacter];
Just change your predicate like this :-
NSPredicate *pred = [NSPredicate predicateWithFormat:#"cityName contains[cd] %#",lastCharacter];

count = 1, but -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array

Here is my fetch request:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Test" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"theId == %#", testId]];
[fetchRequest setEntity:entity];
NSArray *theFetchArray = [[self managedObjectContext] executeFetchRequest:fetchRequest error:nil];
Test *test;
if (theFetchArray.count > 0) {
test = [theFetchArray objectAtIndex:0];
NSLog(#"%#", test.value); //ERROR THROWN HERE
}
"count" is 1 and if I NSLog(#"%#", test), it returns the instance of Test correctly - with "value" present. I set a breakpoint, and both the object within theFetchArray and the test object look like they're correct and contain "value".
Why is this happening?
P.S. - I found this Other StackOverflow post similar to my scenario
This is the EXACT problem I'm experiencing. But no answers, unfortunately.

Error while fetching data from Core Data

I’m working on an dictionary app. this app using core data and I'm very new to core data. In the database, records stored with a single entity called dictionary and dictionary entity has just two attributes “English” & “Meaning”.
So whenever user types some char say a, in UISearchBar, I want to fetch records from data base that starts from “a”, if user types data a than b that I want to fetch records starts from “ab” and so on.
I’m trying same thing by below code:
// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:ENTITY_NAME inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
// retrive the objects with a given value for a certain property
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"%K beginswith[c] %#",#"English",searchText];
[request setPredicate:predicate];
// Edit the sort key as appropriate.
/*NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"English" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];*/
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
/*NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:#"Root"];
aFetchedResultsController.delegate = self;*/
NSError *error = nil;
_searchResult = [managedObjectContext executeFetchRequest:request error:&error];
when this code executes my app crashes with the following error msg:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath English not found in entity <NSSQLEntity TamilEnglishDict id=1>'
EDIT:
this is how my Data Model is...
Any who can guide me to the right path of fetching records properly?
Yes it's case sensitive.
So the correct predicate is the following.
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"%K beginswith[c] %#",#"english", searchText];
or just
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"english beginswith[c] %#", searchText];
but while saving those values in managedObject I wrote '[managedObject
setValue:[obj objectForKey:#"English"] forKey:#"English"]';
So now edit your question and explain me the comment above. What do you mean?
Maybe you could just do
[managedObject setValue:[obj objectForKey:#"English"] forKey:#"english"];
I saw your code & your code is correct, you just have to change Predicate you are using. just replace this code with your predicate & hope your problem is solve. because you want result that conatain "ab" or "a" or "b" so you have to use "contain" in place of "beginswith".
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"%K contains[cd] %#",#"English", searchText];
Let me know if you have any issue.

Core Data Deletion Unsuccessful *easy fix?*

I have a simple XCDataModel that contains one Entity with One Attribute. Essentially, I am saving a series of Dates.
Now, I Know I am adding the NSDates properly because I run a fetch request after adding them and run through the results like so:
for (NSManagedObject *info in fetchedObjects) {
NSLog(#"Name: %#", [info valueForKey:#"attribute"]);
}
And every additional NSDate is accounted for. Example from Log:
2012-06-19 12:40:38.531 Arts Days[47194:16103] Name: 2013-03-27 04:00:00 +0000
2012-06-19 12:40:38.531 Arts Days[47194:16103] Name: 2013-03-01 05:00:00 +0000
2012-06-19 12:40:38.532 Arts Days[47194:16103] Name: 2013-01-01 05:00:00 +0000
Now, when I try to delete an object from Core Data, it proves unsuccessful (by running the same fetch and running through the results again).
Here is the fetch:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Entity" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:366];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"date" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
NSError *error = nil;
[fetchRequest setSortDescriptors:sortDescriptors];
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *object in fetchedObjects) {
if ([[object valueForKey:#"date"] isEqualToDate:date]) {
[managedObjectContext deleteObject:object];
}
}
if (![managedObjectContext save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
Also, the NSLog with Unresolved error contains nil nil...
Do you know what I am doing wrong?
It appears you use two different NSManageObjectContext instances. self.managedObjectContext (an ivar) to set up your fetch request and perform the fetch, but a local instance to do the deleteObject: and save: operations. The local instance managedObjectContext is probably nil and not referring to the same object as the ivar.

Why do I get a NSInvalidArgumentException?

Why do I get a NSInvalidArgumentException with my code below?
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Order dish]: unrecognized selector sent to instance
(void)fetchDishRecords: (NSMutableArray*)array predicate: (NSString*)categoryname
{
// Define our table/entity to use
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Order" inManagedObjectContext:managedObjectContext];
// Setup the fetch request
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
//set predicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"Category=%#", categoryname];
[request setPredicate:predicate];
//set sorting
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"Dish" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[request setSortDescriptors:sortDescriptors];
[sortDescriptor release];
// Fetch the records and handle an error
NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (!mutableFetchResults)
{
// Handle the error.
}
else
{
for(int i=0;i<[mutableFetchResults count];i++)
{
Order *orderObj = [mutableFetchResults objectAtIndex:i];
//NSLog(orderObj.dish);
//NSString* tempStr = orderObj.dish;
[array addObject:orderObj.dish];
}
}
// Save our fetched data to an array
[mutableFetchResults release];
[request release];
[array addObject:orderObj.dish];
Seems to be the culprit...
orderObj is of class Order and the error says it cannot perform selector dish.
Make sure you have a method -(void)dish implemented for your Order class.