NSFetchRequest with NSPredicate not returning any results - nspredicate

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]];

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"];

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

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];
}

Core Data Returns incorrect value (although nearly right)

Okay so I ask the Core Data for a record (userKey), in that record is a PublicKey which I am extracting, however, publicKey ends up being 90% right but has a few extra characters at the beginning and is encapsulated in brackets.
I think my problem is I am getting a pointer rather than the data from the userMatches. Any guidance would be appreciated.
AppDelegate *appdelagate = [[UIApplication sharedApplication]delegate];
context = [appdelagate managedObjectContext];
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:#"KeyData" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
predicate = [NSPredicate predicateWithFormat:#"userKeyCD = %#", userKey];
[request setEntity:entitydesc];
[request setPredicate:predicate];
userMatches = [context executeFetchRequest:request error:&error];
NSString *publicKey = [userMatches valueForKey:#"publicKeyCD"];
Okay so I changed the last line to this and it worked fine;
NSString *publicKey = [[userMatches objectAtIndex:0] valueForKey:#"publicKeyCD"];
I did not show how it was defined but userMatches is an NSArray (sorry). It is used in a similar way further up the code;
NSArray *userMatches = [context executeFetchRequest:request error:&error];
Now I think about it is an array the right type?

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.

edit an attribute in core data

here is my code to edit a particular attribute and save it to the sqlite DB but i can't save the changes to the DB.
-(void)changeMemberKey
{
NSEntityDescription *entityDesc=[NSEntityDescription entityForName:#"Table1" inManagedObjectContext:context];
NSFetchRequest *request=[[NSFetchRequest alloc] init];
NSPredicate *predicate=[NSPredicate predicateWithFormat:#"(member_id=Null)"];
[request setPredicate:predicate];
[request setEntity:entityDesc];
Table1 *matches;
NSError *error;
NSArray *objects=[context executeFetchRequest:request error:&error];
NSLog(#"Object count===%d",[objects count]);
for(int i=0;i<[objects count];i++)
{
matches=[objects objectAtIndex:i];
Table1 *data=(Table1 *)matches;
NSLog(#"Data before===%#",data);
[data setValue:memberKey forKey:#"member_id"];
[context save:&error];
NSLog(#"Data after====%#",data);
data=nil;
}
entityDesc=nil;
request=nil;
matches=nil;
error=nil;
objects=nil;
}
Try to replace the for loop to
for(Table1 * data in objects)
data.member_id = memberKey;
if (! [context save:&error])
NSLog(#"Couldn't save data! Error:%#", [error description]);
Not sure whether it'll work or not, just take a try. Anyway, it's cleaner.

Resources