Unable to fetch specific column that from core data - ios

I have created a an entity called Statutory with four columns namely name,complianceName,statMappingName,country
i want a get all complianceName names that matches a specific statMappingName. Following is my code
NSString *nameToGet = self.statNameArray[indexPath.row] ;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"complianceName = %#", nameToGet];
[fetch setPredicate:predicate];
NSLog(#"n %#",predicate);
NSError *error = nil;
NSArray *results = [[self managedObjectContext] executeFetchRequest:fetch error:&error];
if(results) {
NSLog(#"Entities with that name: %#", results);
} else {
NSLog(#"Error: %#", error);
}
But it is not providing the compliance name specific to that statMappingName. How can I be able to get all complianceName that has a specific statMappingName?

Try this:-
NSString *firstName = statMappingName;
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"firstName == %#", firstName]];

If you want to fetch specific column from core data
You can use the below method:-
NSEntityDescription *entity = [NSEntityDescription entityForName:entityname inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setReturnsObjectsAsFaults:NO];
[request setEntity:entity];
[request setFetchLimit:1];
[request setPredicate:[NSPredicate predicateWithFormat:#"(complianceName LIKE %#)",nametoGet]];
NSError *error = nil;
NSMutableArray *tempDataArr = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
Note:-
*entityname: Your entity name
*self.managedObjectContext : Your managedobjectcontext
To Get All compliance Name use the below method
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:entityName];
[fetchRequest setReturnsObjectsAsFaults:NO];
NSMutableArray *tempDataArr =[NSMutableArray new];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"(ANY complianceName LIKE %#)",nametoGet]];
tempDataArr = [[self.managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

try these code for contains statMappingName
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"complianceName contains[c] %#", statMappingName];

Related

Save the result of setPredicate to NSString

I have created NSPredicate to search the string in my coredata.
so in this case does anyone know how to save the result [fetchRequest setPredicate:predicate]; in NSString.
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name CONTAINS[cd] %#",
mytext];
[fetchRequest setPredicate:predicate];
Write Your Table Name in #"YOUR_ENTITY_NAME"
Make sure that your table contains name column
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"YOUR_ENTITY_NAME"];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"name CONTAINS[cd] %#", mytext]];
NSMutableArray *arrResult = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSLog(#"%#", arrResult); //output
I think this will help you
NSArray *fetchedObjects;
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"your entity" inManagedObjectContext: context];
[fetch setEntity:entityDescription];
[fetch setPredicate:[NSPredicate predicateWithFormat:#"name CONTAINS[cd] %#", mytext]];
NSError * error = nil;
fetchedObjects = [context executeFetchRequest:fetch error:&error];
if([fetchedObjects count] == 1)
NSLog(#"%#",[fetchedObjects objectAtIndex:0]);

Subquery Predicate Core Data

I have two Entity models "Content" and "LessonsContent" with no relationship between them. Both entities have common attribute "contentID" of NSNumber type. I am fetching all contents objects from "Content" entity for given predicate and storing these objects in contents array. I was successful in doing so.
Now, I want to fetch all lessonsContent objects from "LessonsContent" entity whose contentIds are present in contents array.
I am using following code:
NSPredicate * predicate = [NSPredicate predicateWithFormat:#"(contentType == %#)", #"Games"];
NSError * error;
NSFetchRequest * request = [[NSFetchRequest alloc] initWithEntityName:NSStringFromClass([Content class])];
[request setPredicate:predicate];
[request setReturnsObjectsAsFaults:NO];
NSArray *contents = [[DELEGATE managedObjectContext] executeFetchRequest:request error:&error];
if(error){ NSLog(#"Error in fatching data");}
//predicate = [NSPredicate predicateWithFormat:#"Content.contentID IN %#", contents];
predicate = [NSPredicate predicateWithFormat:#"(SUBQUERY(contents, $x, $x.Content.contentID IN %#).#count != 0)",contents];
request = [[NSFetchRequest alloc] initWithEntityName:NSStringFromClass([LessonsContent class])];
[request setPredicate:predicate];
NSArray * mappingArray = [[DELEGATE managedObjectContext] executeFetchRequest:request error:&error];
NSLog(#"mappingArray %#", mappingArray);
But app is crashing. Please suggest appropriate solution.
Thanks in advance.
You have to get an array of contentID's first. Then use IN.
NSArray *contents = [[DELEGATE managedObjectContext] executeFetchRequest:request error:&error];
NSArray * allContentIDs = [contents valueForKey:#"contentID"];
then use the second predicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"contentID IN %#", allContentIDs];
[request setPredicate:predicate];
Hope this helps.

How do we Retrive Data Which is Saved By Using Core Data in iOS

I am New to Core Data.I have Developed an application. In my application i am having Registration, Login, Forgot password Forms.
In Registration Form i Write this code for registration.
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:#"User" inManagedObjectContext:context];
NSManagedObject *newuser = [[NSManagedObject alloc]initWithEntity:entitydesc insertIntoManagedObjectContext:context];
[newuser setValue:self.registerUsername.text forKey:#"username"];
[newuser setValue:self.registerPassword.text forKey:#"password"];
[newuser setValue:self.registerConfirmPassword.text forKey:#"confirmpassword"];
[newuser setValue:self.registerMobileNumber.text forKey:#"mobilenumber"];
NSError *error;
[context save:&error];
In Login Form i write this Code:
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:#"User" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entitydesc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"username like %# and password like %#",self.logUsername.text,self.logPassword.text];
[request setPredicate:predicate];
NSError *error;
NSArray *matchingData = [context executeFetchRequest:request error:&error];
if(matchingData.count<=0)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error!" message:#"Username and password does not match" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
else
{
NSString *username;
NSString *password;
for(NSManagedObject *obj in matchingData)
{
username = [obj valueForKey:#"username"];
password = [obj valueForKey:#"password"];
}
SecurityHome *securityhome = [[SecurityHome alloc]init];
[self.navigationController pushViewController:securityhome animated:YES];
}
}
Both were Working fine. Now i want to Display Password in Forgot password page if the user entered Username and Mobile number Correctly.How Can i Achieve this?
Set example predicate and sort orderings...
NSNumber *minimumSalary = ...;
NSPredicate *predicate = [NSPredicate predicateWithFormat:
#"(lastName LIKE[c] 'Worsley') AND (salary > %#)", minimumSalary];
[request setPredicate:predicate];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
initWithKey:#"firstName" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
NSError *error = nil;
NSArray *array = [moc executeFetchRequest:request error:&error];
if (array == nil)
{
// Deal with error...
}
You should have done some 'googling' before asking this question. Any how,Let me do it for you. Here you go.
Core Data NSFetchResult guide for developer
Ray wenderlich- Really nice tutorial
In both of the listed links, I am trying to suggest NSFetchResultControllers, as they are fast & easy. Here you can see the difference
Without NSFetchResultController,
NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:#"Employee" inManagedObjectContext:moc];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
// Set example predicate and sort orderings...
NSNumber *minimumSalary = ...;
NSPredicate *predicate = [NSPredicate predicateWithFormat:
#"(lastName LIKE[c] 'Worsley') AND (salary > %#)", minimumSalary];
[request setPredicate:predicate];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
initWithKey:#"firstName" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
NSError *error = nil;
NSArray *array = [moc executeFetchRequest:request error:&error];
if (array == nil)
{
// Deal with error...
}
With NSFetchresultController
[[self managedObjectContext] fetchObjectsForEntityName:#"Employee" withPredicate:
#"(lastName LIKE[c] 'Worsley') AND (salary > %#)", minimumSalary];
These examples are for Famous employee table. Translate the code as per your requirement. If you are unable to work around with this code for any reason, let me know..
You can use this code for fetching details and pass the object to Forgot class and show there.
-(User*)getUserCredentialDetails:(NSUInteger)mobilenumber
{
NSError *error = nil;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"User" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"mobilenumber = %d",mobileNumber];
[request setPredicate:predicate];
NSArray * resultArray = [managedObjectContext executeFetchRequest:request error:&error];
[request release];
if (error != nil)
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
return [resultArray lastObject];
}

Weird NSPredicate Behavior?

I have an NSPredicate which checks the relationship of an entity called "Eval(whosEval)" and if the relationship whosEval matches the full name of another entity, "Athlete(evals)", with the athlete that was selected, it displays all the Evals for that particular Athlete. Unfortunately, my predicate is doing weird things. If I have no athletes, and then add one, then add an eval, it shows all their evals, then I add another, the second athlete won't display any evals I added for that athlete and instead displays all of the other athlete's evals. Am I doing something incorrectly? All evals view controller is displayed prior to add Eval view controller.
allEvals.m
-(void)viewWillAppear:(BOOL)animated{
self.title = [NSString stringWithFormat:#"%#'s Evaluations",_athletesFullName];
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
_managedObjectContext = [appDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSFetchRequest *athleteRequest = [[NSFetchRequest alloc] init];
[athleteRequest setEntity:[NSEntityDescription entityForName:#"Athlete" inManagedObjectContext:_managedObjectContext]];
NSError *athleteError = nil;
NSPredicate *athletePredicate = [NSPredicate predicateWithFormat:#"full == %#", _athletesFullName];
[athleteRequest setPredicate:athletePredicate];
NSArray *results = [_managedObjectContext executeFetchRequest:athleteRequest error:&athleteError];
Athlete *currentAthlete = [results objectAtIndex:0];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"whosEval == %#", currentAthlete];
[request setPredicate:predicate];
NSEntityDescription *eval = [NSEntityDescription entityForName:#"Eval" inManagedObjectContext:_managedObjectContext];
[request setEntity:eval];
NSSortDescriptor *sortDescriptor =
[[NSSortDescriptor alloc] initWithKey:#"date_recorded"
ascending:NO
selector:#selector(localizedCaseInsensitiveCompare:)];
NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[_managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil){
//handle error
}
[self setEvalArray:mutableFetchResults];
[self.tableView reloadData];
}
addEval.m
-(void)saveEval{
//insert saving attributes here
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
_managedObjectContext = [appDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"Athlete" inManagedObjectContext:_managedObjectContext]];
NSError *error = nil;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"full == %#", _whichAthletesEval];
[request setPredicate:predicate];
NSArray *results = [_managedObjectContext executeFetchRequest:request error:&error];
Athlete *currentAthlete = [results objectAtIndex:0];
[eval setWhosEval:currentAthlete];
NSLog(#"This Eval Belongs to: %#",eval.whosEval);
NSLog(#"whichAthletesEval value is equal to: %#", _whichAthletesEval);
}
NSError *error = nil;
if(![_managedObjectContext save:&error]){
//handle dat error
}
[self.navigationController popViewControllerAnimated:YES];
}
I have left inline comments (signed off with my initials) in your viewWillAppear: method that point out what I believe to be errors. Essentially, you fetch an arbitrary athlete instead of the one that's been selected (which I'm assuming is the source of _athletesFullName. As far as your saveEval method, your naming conventions are tough to follow so it's not clear to me what further issues you could have here.
-(void)viewWillAppear:(BOOL)animated{
self.title = [NSString stringWithFormat:#"%#'s Evaluations",_athletesFullName];
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
_managedObjectContext = [appDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSFetchRequest *athleteRequest = [[NSFetchRequest alloc] init];
[athleteRequest setEntity:[NSEntityDescription entityForName:#"Athlete" inManagedObjectContext:_managedObjectContext]];
NSError *athleteError = nil;
// No predicate is used at all for the contents of results here - see below - CV
NSArray *results = [_managedObjectContext executeFetchRequest:athleteRequest error:&athleteError];
NSPredicate *athletePredicate = [NSPredicate predicateWithFormat:#"full == %#", _athletesFullName];
// This predicate never used as another predicate is set a few lines below - CV
[request setPredicate:athletePredicate];
// currentAthlete will not necessarily be the one conforming to athletePredicate
// just the first in the array of every Athlete you've fetched - CV
Athlete *currentAthlete = [results objectAtIndex:0];
// because currentAthlete is arbitrary, you're now creating a predicate you likely didn't intend to - CV
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"whosEval == %#", currentAthlete];
[request setPredicate:predicate];
NSEntityDescription *eval = [NSEntityDescription entityForName:#"Eval" inManagedObjectContext:_managedObjectContext];
[request setEntity:eval];
NSSortDescriptor *sortDescriptor =
[[NSSortDescriptor alloc] initWithKey:#"date_recorded"
ascending:NO
selector:#selector(localizedCaseInsensitiveCompare:)];
NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[_managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil){
//handle error
}
[self setEvalArray:mutableFetchResults];
[self.tableView reloadData];
}

NSFetchRequest, possible to filter by aggregate functions?

I am trying to pull all the Actions which belong to the latest Session.
In SQL this would be a simple JOIN ... WHERE Session.startTime = MAX(Session.startTime), but with Core Data I can't figure out how to do this without resorting to two steps as below. Any ideas?
// Step 1. Get the latest session
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"Session" inManagedObjectContext:self.managedObjectContext]];
[request setSortDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"startTime" ascending:NO]]];
[request setFetchLimit:1];
Session *lastSession = nil;
NSArray *objects = [self.managedObjectContext executeFetchRequest:request error:NULL];
if ([objects count] > 0)
{
NSLog(#"max: %#", [objects objectAtIndex:0]);
lastSession = [objects objectAtIndex:0];
}
// Step 2. Get that session's actions
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Action" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sectionSort = [[NSSortDescriptor alloc] initWithKey:#"session.startTime" ascending:NO selector:nil];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:#"startTime" ascending:NO selector:nil];
[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sectionSort, sort, nil]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"session.startTime = %#", lastSession.startTime];
//**Can't I do something like this instead?**
//NSPredicate *predicate = [NSPredicate predicateWithFormat:#"session.startTime = session.#max.startTime"];
[fetchRequest setPredicate:predicate];
[fetchRequest setFetchBatchSize:10];
[self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:#"session.startTime" cacheName:#"ActionHistory"];
self.fetchedResultsController.delegate = self;
NSError *error;
if (![self.fetchedResultsController performFetch:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort(); // Fail
}
Edit: I do need to stick with using NSFetchedResultsController due reasons not fully detailed above.
I would advise you to make a relationship beetwen Session and Action.
Then, after you fetch the session you need, you could get all that session's actions as easy ss lastSession.actions.
Edit
Maybe you can do
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"session = %#",lastSession];

Resources