I Have the following model:
I need to get all PT objects WHERE none of hasStatus objects belongs to groupId = 4. So, none of PTStatus object property status.group.groupId = 4.
I've tried several ways, but it's returning PTs that have some PTSTatus where groupId = 4.
For example:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:#"PT" inManagedObjectContext:context];
request.predicate = [NSPredicate predicateWithFormat:#"NONE hasStatus.status.group.groupId == %#",
[NSNumber numberWithInt:4]];
Any help?
Related
In a section of my data model I'm using -
Department <-->> Person <<-->> Project
I want to list all person's of departmentA that have at least 1 project in common with persons in departmentB. For example, of the list of projects personA has there needs to be at least 1 person from departmentB who also has the project. If a personB also has that project then personA is on the list. I've been struggling for a while with subquery and the direction I'm going is below. It fails with 'to-many key not allowed' other attempt have given me 'parse issue'.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Project" inManagedObjectContext:_managedObjectContext];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"projectToPerson.personToDepartment = %#", departmentB];
[fetchRequest setPredicate:predicate];
NSError *error = nil;
NSArray *projects = [_managedObjectContext executeFetchRequest:fetchRequest error:&error];
NSFetchRequest *fetchRequest2 = [[NSFetchRequest alloc] init];
NSEntityDescription *entity2 = [NSEntityDescription
entityForName:#"Person" inManagedObjectContext:_managedObjectContext];
[fetchRequest2 setEntity:entity2];
NSPredicate *predicate2 = [NSPredicate predicateWithFormat:#"personToDepartment = %# AND SUBQUERY(personToProject, $x, $x.projectName = %#).#count >0", departmentA,projects];
[fetchRequest2 setPredicate:predicate2];
I'm attempting to get an array of all projects and then list all persons of departmentA with a project that matches. Is this possible, and is this the right direction?
I want to store data from a text field. And then use this data to populate the text in a label inside a view controller. Is this possible? Ive messed around with it, but nothing seems to work. Any thoughts? Here are my two methods...
- (IBAction)saveButton:(id)sender {
CoreDataStack *coreDataStack = [CoreDataStack defaultStack];
NSManagedObject *noteEntry = [NSEntityDescription insertNewObjectForEntityForName:#"Notes" inManagedObjectContext:coreDataStack.managedObjectContext];
[noteEntry setValue:_notesField.text forKey:#"notes"];
NSError *error = nil;
// Save the object to persistent store
if (![coreDataStack.managedObjectContext save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
[coreDataStack saveContext];
}
Here is my view did load method:
- (void)viewDidLoad
{
[super viewDidLoad];
CoreDataStack *coreDataStack = [CoreDataStack defaultStack];
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:#"Notes"];
Notes *entry = [NSEntityDescription insertNewObjectForEntityForName:#"Notes" inManagedObjectContext:coreDataStack.managedObjectContext];
_outputLabel.text = entry.notes;
}
Your code in the saveButton: method seems OK. But your code in the viewDidLoad method seems wrong. Are you trying to do the following?
- (void)viewDidLoad {
[super viewDidLoad];
CoreDataStack *coreDataStack = [CoreDataStack defaultStack];
//First way to init your fetchRequest:
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:#"Notes"];
//Second way to init your fetchRequest:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Notes" inManagedObjectContext:coreDataStack];
[fetchRequest setEntity:entity];
//Having a NSEntityDescription object can be usefull if you need to group your data, for example
//Set some predicates, if necessary
//Set some sortdescriptors, if necessary
NSError *error;
NSArray *resultsArray = [coreDataStack executeFetchRequest:request error:&error];
NSLog(#"%#", resultsArray);
_outputLabel.text = [[resultsArray firstObject] notes]; //if your array can only have one object
}
The NSLog will give you the structure of your fetch array (I can't guess it). You will then be able to set _outputLabel.text.
Answer by #user1966109 is exactly correct answer what you are looking for. Since you need to show the text in a label and for that you need to set predicate to get a single row. Set the predicate as below
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"value == abc"];//considerin abc is the word you are looking for.
request.predicate = predicate;
//then execute the query.
I am new to core data and am still trying to get my head around it. I have a problem that I have spent hours on trying to solve. I just can't seem to solve it and was hoping someone could help me.
I can't post images yet so here is a link to my data model:
http://yourpcsolution.net/model.png
Each relationship has an inverse. A Game can have many Periods and a Period can have many Players. A Player can be in more than one Period.
Here is my code for populating DB:
- (void) prepareDB {
Games *game = [NSEntityDescription insertNewObjectForEntityForName:#"Games" inManagedObjectContext:self.managedObjectContext];
game.date = [NSDate date];
game.name = #"Game 1";
Periods *period = [NSEntityDescription insertNewObjectForEntityForName:#"Periods" inManagedObjectContext:self.managedObjectContext];
period.date = [NSDate date];
period.name = #"1st Period";
NSMutableSet *gameSet = [[NSMutableSet alloc] initWithObjects:period, nil];
game.periods = gameSet;
Players *player = [NSEntityDescription insertNewObjectForEntityForName:#"Players" inManagedObjectContext:self.managedObjectContext];
player.name = #"Player1";
NSMutableSet *playerSet = [[NSMutableSet alloc] initWithObjects:player, nil];
period.players = playerSet;
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}
I think that's the correct way to add data because when looking at the sql db the data is there. My problem is in trying to retrieve the players that belong to each period. Because Periods is a set in Games and Players is a set in Periods in core data. So I can't retrieve players by going: game.periods.players
Here is my code for retrieving a Period and in the xcode log i am getting a fault:
"Relationship 'players' fault on managed object (0x8e72bc0) <Periods: 0x8e72bc0>
(entity: Periods; id: 0x8e727c0 <x-coredata://7F63902B-FCB6-4ACA-BB40-904755D37A4A/Periods/p1>;
data: {\n date = \"2013-07-09 19:35:48 +0000\";\n
games = \"0x8e6d760 <x-coredata://7F63902B-FCB6-4ACA-BB40-904755D37A4A/Games/p1>\";\n
name = \"1st Period\";\n players = \"<relationship fault: 0x9840330 'players'>\";\n})"
My Code for retrieving a Period:
NSString *firstPeriod = #"1st Period";
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name == %#", firstPeriod];
[request setEntity:[NSEntityDescription entityForName:#"Periods" inManagedObjectContext:self.managedObjectContext]];
[request setPredicate:predicate];
NSArray *period = [self.managedObjectContext executeFetchRequest:request error:&error];
I'm not sure how to proceed from here to retrieve the players. I know how to retrieve what Periods belong to each game but I don't know how to retrieve the players that belong to a period. I have been trying for days to figure this out and it's just not working.
Is my data model correct? How should I be retrieving the data? Any help or advice is appreciated.
To fetch all players of a given period, the following should work:
NSString *firstPeriod = #"1st Period";
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"Players" inManagedObjectContext:self.managedObjectContext]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"ANY periodsin.name == %#", firstPeriod];
[request setPredicate:predicate];
NSArray *players = [self.managedObjectContext executeFetchRequest:request error:&error];
"ANY" in the predicate is necessary because each player is connected to multiple Periods.
Remark: The data type of a to-many relationship is NSSet, not NSMutableSet.
ADDED: To fetch all periods for a given player, you can use the following fetch request:
Players *givenPlayer = ... ; // the given player
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"Periods" inManagedObjectContext:self.managedObjectContext]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"ANY players == %#", givenPlayer];
[request setPredicate:predicate];
NSArray *periods = [self.managedObjectContext executeFetchRequest:request error:&error];
Alternatively, you can access the relationship directly:
Players *givenPlayer = ... ; // the given player
NSArray *periods = [givenPlayer.periodsin allObjects]; // "allObjects" converts NSSet to NSArray
How does one fetch a set of unique managed objects by requesting a specific attribute to be checked.
e.g. A number of people objects and I would like to retrieve all the unique names, one managed object for each unique name, sorted by name.
What about using a request like this
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Person" inManagedObjectContext:managedObjectContext];
request.entity = entity;
request.propertiesToFetch = [NSArray arrayWithObject:[[entity propertiesByName] objectForKey:#"name"]];
request.returnsDistinctResults = YES;
request.resultType = NSDictionaryResultType;
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptors]];
NSError *error = nil;
NSArray *distinctResults = [managedObjectContext executeFetchRequest:request error:&error];
// Use distinctResults
Try and let me know.
P.S. Code is ARC enabled. If you are not using it, call release when necessary.
I'm working with core data and I try to get last 20 records using setFecthLimit but in these last records I want to get count of unreads, I use this
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Post" inManagedObjectContext:_managedObjectContext];
[request setEntity:entity];
[request setFetchLimit:20];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"isRead = NO OR isRead = NIL"];
[request setPredicate:predicate];
NSError *error = nil;
NSMutableArray *records = [[_managedObjectContext
executeFetchRequest:request
error:&error] mutableCopy];
but it always return me 20, can anyone help me please?
A simple solution is to remove the predicate. Grab 20 objects and then filter them based on the predicate.
For example:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Post" inManagedObjectContext:_managedObjectContext];
[request setEntity:entity];
[request setFetchLimit:20];
NSError *error = nil;
NSArray *records = [_managedObjectContext executeFetchRequest:request
error:&error];
// do some error checking here...
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"isRead = NO OR isRead = nil"];
// [NSPredicate predicateWithFormat:#"isRead = %#", [NSNumber numberWithBool:NO]];
NSArray *filteredRecords = [records filteredArrayUsingPredicate:predicate];
I think you have a typo in your predicate format:
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Post"]
request.fetchLimit = 20;
request.predicate = [NSPredicate predicateWithFormat:#"(isRead == NO) OR (isRead == NULL)"];
NSSortDescriptor = [...insert your sort descriptor code here...]
request.sortDEscriptos = #[sd];
And remember to sort, such that you get the last 20, not just a random 20.