NSInvalidArgumentException', reason: 'Invalid predicate: nil RHS, need help figuring this out - nspredicate

I've read other posts about this crash having something to do with the predicate returning nil but im unable to figure this out with my app. Can someone please help me with this?
static NSString *const KJMWorkoutCategorySectionKeyPath = #"workoutCategory";
- (NSFetchedResultsController *)fetchedResultsControllerWithSearchString:(NSString *)searchString {
NSManagedObjectContext *sharedContext; // my NSManagedObjectContext instance...
NSFetchRequest *request = [NSFetchRequest new];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Workouts"
inManagedObjectContext:sharedContext];
request.entity = entity;
request.predicate = [NSPredicate predicateWithFormat:#"(workoutName CONTAINS[cd] %#)", searchString];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:KJMWorkoutCategorySectionKeyPath ascending:YES];
request.sortDescriptors = #[sortDescriptor];
NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:sharedContext
sectionNameKeyPath:KJMWorkoutCategorySectionKeyPath
cacheName:nil];
fetchedResultsController.delegate = self;
NSError *error = nil;
if (![fetchedResultsController performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, error.userInfo);
abort();
}
return fetchedResultsController;
}

The error message indicates that searchString is nil in
NSPredicate *filterPredicate = [NSPredicate
predicateWithFormat:#"(workoutName CONTAINS[cd] %#)", searchString];
If the intention is to display all objects if no search string is given, you should
just not assign a predicate to the fetch request in that case:
if ([searchString length] > 0) {
NSPredicate *filterPredicate = [NSPredicate
predicateWithFormat:#"(workoutName CONTAINS[cd] %#)", searchString];
[request setPredicate:filterPredicate];
}

Related

Storing JSON response in iOS error

I am making a call to an online php from my iOS app. In my output window I see the JSON Response with the data. But I need to store the NSString in my userdefaults but it is coming up NULL.
In this code the NSLog(#"JSON Response is %#", responseData); returns the json data just fine and I see the ipixid. But in the NSLog (#"ipixid is %#", ilixid); it returns ipixid is (null)
NSString *post =[[NSString alloc] initWithFormat:#"email=%#", strValue];
NSLog(#"PostData: %#",post);
NSURL *url1=[NSURL URLWithString:#"http://www.ipixsocial.com/membership/getresult.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url1];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"JSON Response is %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
// NSString *username = [(NSString *) [jsonData objectForKey:#"email"]init];
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"uid"] integerValue];
NSString* ipixid = [jsonData objectForKey:#"ipixid"];
[[NSUserDefaults standardUserDefaults] setObject:ipixid forKey:#"ipixid"];
NSLog (#"ipixid is %#", ipixid);
Don't ignore the "error" parameter you're passing to the parser. Also check that "jsonData" is not nil. I'm think that parsing is failing and because you're ignoring it and assuming jsonData is valid you're getting nil for [jsonData objectForKey:#"ipixid"];

NSFetchRequest with NSPredicate not returning any results

The following NSFetchRequest does not return any results into the array. I suspect something is wrong with the syntax of NSPredicate. Any ideas?
-(NSManagedObject*)requestTheSingleEntity:(NSString *)entityDescription ForWhichIntegerAttribute:(NSString *)attribute isEqualTo:(int)value
{
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *e = [[model entitiesByName] objectForKey:entityDescription];
[request setEntity:e];
NSPredicate *p = [NSPredicate predicateWithFormat:#"(%# == %#)", attribute, [NSNumber numberWithInt:value]];
[request setPredicate:p];
NSError *er;
NSArray *results = [context executeFetchRequest:request error:&er];
NSLog(#"the count of results = %d", [results count]);
You have to use %K for attributes, not %#:
NSPredicate *p = [NSPredicate predicateWithFormat:#"%K == %#", attribute, [NSNumber numberWithInt:value]];

Retrieving NSImage from CoreData - Mac OS X

I'm trying to add images into core data and load it when needed. I'm currently adding the NSImage to the core data as follows:
Thumbnail *testEntity = (Thumbnail *)[NSEntityDescription insertNewObjectForEntityForName:#"Thumbnail" inManagedObjectContext:self.managedObjectContext];
NSImage *image = rangeImageView.image;
testEntity.fileName = #"test";
testEntity.image = image;
NSError *error;
[self.managedObjectContext save:&error];
Thumbnail is the entity name and I have two attributes under the Thumbnail entity - fileName(NSString) and image (id - transformable).
I'm trying to retreive them as below:
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *imageEntity = [NSEntityDescription entityForName:#"Thumbnail" inManagedObjectContext:[context valueForKey:#"image"]];
[fetchRequest setEntity:imageEntity];
NSError *error;
NSArray * array = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (array == nil) {
NSLog(#"Testing: No results found");
}else {
_coreDataImageView.image = [array objectAtIndex:0];
}
I end up with this error:
[<NSManagedObjectContext 0x103979f60> valueForUndefinedKey:]: this class is not key value coding-compliant for the key image.
The image is added but couldn't retrieve.
Any idea on how to go about with this? Am I doing it right ?
The error is in this line
NSEntityDescription *imageEntity = [NSEntityDescription entityForName:#"Thumbnail"
inManagedObjectContext:[context valueForKey:#"image"]];
You cannot apply valueForKey:#"image" to a managed object context. You have to apply it to the fetched objects (or use the image property of the fetched object).
Note also that executeFetchRequest: returns nil only if an error occurs. If no entities are found, it returns an empty array.
NSEntityDescription *imageEntity = [NSEntityDescription entityForName:#"Thumbnail" inManagedObjectContext:context];
[fetchRequest setEntity:imageEntity];
NSError *error;
NSArray * array = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (array == nil) {
NSLog(#"Testing: Fetch error: %#", error);
} else if ([array count] == 0) {
NSLog(#"Testing: No results found");
}else {
Thumbnail *testEntity = [array objectAtIndex:0];
NSImage *image = testEntity.image;
_coreDataImageView.image = image;
}

Xcode - filter an NSFetchRequest and select each object

I am trying to filter a fetchRequest.
I'm at the point where the result is loaded into an NSArray.
However, I need to parse the array to pull out the individual items - right now, they look as if they were one object.
The code I'm using to get to this point is:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSManagedObjectContext *moc = coreDataController.mainThreadContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Category" inManagedObjectContext:moc];
[request setEntity:entity];
// Order the events by name.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
[request setSortDescriptors:#[sortDescriptor]];
// Execute the fetch -- create a mutable copy of the result.
NSError *error = nil;
NSArray *categories = [[moc executeFetchRequest:request error:&error] mutableCopy];
if (categories == nil) {
NSLog(#"bugger");
}
NSObject *value = nil;
value = [categories valueForKeyPath:#"name"];
This results as follows:
value = (
)
[DetailViewController loadPickerArray]
[AppDelegate loadPickerArray]
value = (
"Cat Two",
"Cat Three",
"Cat One",
"Cat Four"
)
Also, please note that the first time this ran, there were no results. I get that about 50% of the time.
Thanks for any help.
There are several methods you can filter your data.
The preferred way is to use a predicate for your search. This will give you the best performance.
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSManagedObjectContext *moc = coreDataController.mainThreadContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Category" inManagedObjectContext:moc];
[request setEntity:entity];
// Order the events by name.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name CONTAINS[CD] %#", #"Cat"]; //This will return all objects that contain 'cat' in their name property.
[request setPredicate:predicate];
[request setSortDescriptors:#[sortDescriptor]];
// Execute the fetch -- create a mutable copy of the result.
NSError *error = nil;
NSArray *categories = [moc executeFetchRequest:request error:&error];
if (categories == nil) {
NSLog(#"bugger");
}
//Here you have the objects you want in categories.
for(Category *category in categories)
{
NSLog(#"Category name: %#", category.name);
}
If you wish to filter using an array, the following is possible also:
NSMutableArray *categories = [[moc executeFetchRequest:request error:&error] mutableCopy];
[categories filterUsingPredicate:[NSPredicate predicateWithFormat:[NSPredicate predicateWithFormat:#"name CONTAINS[CD] %#", #"Cat"]]
//Now, the only objects left in categories will be the ones with "cat" in their name property.
I recommend reading the Predicates Programming Guide, as predicates are very powerful, and it is much more efficient to filter your results in the store.

NSDistantObject enumeration

I was make communication for client-server application and have strange problem.
here is a code where i pickup objects.
- (byref NSArray*)objectsOfName:(bycopy NSString*)name
withPredicate:(bycopy NSPredicate*)predicate;
{
NSManagedObjectContext *context = [self managedObjectContext];
NSError *error = nil;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:name
inManagedObjectContext:context]];
[request setPredicate:predicate];
NSArray *results = [context executeFetchRequest:request error:&error];
[request release], request = nil;
if (error) {
NSLog(#"%#:%# Error on fetch %#", [self class], NSStringFromSelector(_cmd), error);
return nil;
}
//NSLog(#"%#:%# Result of fetch is %#", [self class], NSStringFromSelector(_cmd), results);
return results;
}
Here is pickup:
NSArray *destinations;
#ifdef SNOW_CLIENT
destinations = [server objectsOfName:#"DestinationsListWeBuy" withPredicate:predicate];
If i do
NSLog(#"Destination:%#\n",destinations);
i seen all objects in log.
If i try to do
NSLog(#"all:%#\n%#\n%#\n",[[destinations objectAtIndex:0] valueForKey:#"rate"],[[destinations objectAtIndex:0] valueForKey:#"lastUsedACD"],[[destinations objectAtIndex:0] valueForKey:#"lastUsedCallAttempts"]);
i seen attributes also.
But, if i try to do loop around objects:
for (NSManagedObject *dest in destinations)
{
NSLog(#"all:%#\n%#\n%#\n",[dest valueForKey:#"rate"],[dest valueForKey:#"lastUsedACD"],[dest valueForKey:#"lastUsedCallAttempts"]);
i have EXC_BAD_ACCESS in this part of code:
for (NSManagedObject *dest in destinations)
all debug technic, which i know, don't give me possibility to understand, what happened. (NSZombieEnabled = YES)
if i do loop at another manner:
for (NSUInteger count = 0;count < [destinations count]; count++)
NSLog(#"all:%#\n%#\n%#\n",[[destinations objectAtIndex:count] valueForKey:#"rate"],[[destinations objectAtIndex:count] valueForKey:#"lastUsedACD"],[[destinations objectAtIndex:count] valueForKey:#"lastUsedCallAttempts"]);
i seen all keys without exception. All nsmanagedobject's is subclassed.
If i need implement encodeWithCored method for all subclasses, examples is appreciated.
*UPDATE for Marcus *
This is how i receive objects from server side:
- (byref NSArray*)allObjects
{
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setValue:#"Failed to initialize the store" forKey:NSLocalizedDescriptionKey];
[dict setValue:#"There was an error building up the data file." forKey:NSLocalizedFailureReasonErrorKey];
NSError *error = [NSError errorWithDomain:#"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
[[NSApplication sharedApplication] presentError:error];
return nil;
}
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init];
[moc setPersistentStoreCoordinator:coordinator];
[moc setUndoManager:nil];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:#selector(mergeChangesForClient:)
name:NSManagedObjectContextDidSaveNotification
object:thirdMOC];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Carrier"
inManagedObjectContext:moc];
[request setEntity:entity];
[request setIncludesSubentities:YES];
NSError *error = nil;
NSArray *objects = [moc executeFetchRequest:request error:&error];
[request release], request = nil;
for (NSManagedObject *carrier in objects) {
NSSet *destinations = [carrier valueForKeyPath:#"destinationsListForSale"];
for (NSManagedObject *destination in destinations) [destination addObserver:self forKeyPath:#"rate" options:NSKeyValueObservingOptionNew context:nil];
}
if (error) {
NSLog(#"%#:%# error: %#", [self class], NSStringFromSelector(_cmd), error);
return nil;
}
return objects;
}
This is what i do with them on client side:
NSArray *allObjects = [server allObjects];
[carrierArrayController setContent:allObjects];
There is no serialization in this case. Any other ways (like send copy of server moc to client side doesn't work, it just generate exceptions on main.c).
p.s. many thanks to Marcus for his Core Data book.
unrecognized selector sent to class 0x1000a2ed8 2011-03-17 02:15:18.566 snowClient[19380:903] +[AppDelegate encodeWithCoder:]: unrecognized selector sent to class 0x1000a2ed8
That is not a core data problem. That is an error in your code where you are trying to call a method on an object that does not respond to that method. You need to track that down as it appears that you are trying to serialize your AppDelegate.
Update
What kind of class is 0x1000a2ed8? Break on the exception and print out the object to see what it is. Again, this is not a core data error directly, it is sending a messages to an object that does not respond to that message. It is possible that Core Data no longer allows you to send Managed objects across as distributed objects. It is possible that this is simply an issue with an over-released object. No way to know without further investigation.
Step one: Find out what object 0x1000a2ed8 is and see if the object changes from one run to the next.

Resources