I have an app using coreData fine.
I have this relationship:
company <--->> visitors
now, I need to find specific visitors for an specific company, I can fetch visitors starting with some string pattern,
But how to find the ones for a specific company?
here my code
- (void)searchAvailableDataFullName:(NSTimer*)timer
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"fullName BEGINSWITH [c] %#",self.nameTF.text];
//sort descriptor!
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"fullName" ascending:YES selector:#selector(localizedCaseInsensitiveCompare:)];
//the relationship of interest??
Visitor *theVisitor = nil;
theVisitor.company = self.selectedCompany;
NSMutableArray *fullNamesArray = [NSMutableArray arrayWithArray:[Visitor allWithPredicate:predicate sortDescriptors:#[sortDescriptor]]];
Visitor *visitorName;
NSMutableArray *dataArray = [NSMutableArray array];
for (visitorName in fullNamesArray) {
NSLog(#"tus visitors:: %#", visitorName.fullName);
[dataArray addObject:visitorName.fullName];
}
}
I don't have my Mac in front of me atm but it should be something like:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"visitors.fullName BEGINSWITH [c] %# && visitors.CompanyName BEGINSWITH [c] %#",self.nameTF.text, companyNameTextObject];
Hope that's 100% right, if not you can kind of get the gist of it. You can use the "table.relationshipProperty" to search the relationship.
Apple Predicate Programming Guide
There's some more info there, just check out the "Joins" section. Hope that helps!
Related
I have a Core Data object Contact
Contact
=======
fullName
I'm using a NSFetchedResultsController to show a list of contacts.
I now want to add search option that behave as follow:
If user search for the string "da", the results should be:
Aaron David
Bert Daniels
Dana
John David
So the search result is alphabetic sorted strings that has a word starting with "da"
I remember watching a WWDC session showing how to create a Word object and store each word independently, but I'm trying to avoid this approach.
So my question is, can I do such a search with my current model structure and some predicate magic, or I must store the fullName as separate words?
This is what I do:
NSMutableArray *predicateArray = [NSMutableArray array];
if(searchString.length)
{
for (NSString* searchStringPart in [searchString componentsSeparatedByString:#" "])
{
if([searchStringPart length] > 0)
{
[predicateArray addObject:[NSPredicate predicateWithFormat:#"name CONTAINS[cd] %#", searchStringPart]];
}
}
filterPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:#[filterPredicate, [NSCompoundPredicate andPredicateWithSubpredicates:predicateArray]]];
}
And for sorting:
NSSortDescriptor *sort = [[[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES] autorelease];
NSArray* sortDescriptors = #[sort];
....
[fetchRequest setSortDescriptors:sortDescriptors];
You need to use predicate for filtered word by name in your array. Use below:-
//Assuming you have store the name in one array
NSArray *names=#[#"Aaron David",#"Bert Daniels",#"Dana",#"John David"];
//Now use contains in predicate for filtered words
//On the basis of search string it will filtered accordingly. lets Say yourStringValue=#"on"
NSPredicate *pd=[NSPredicate predicateWithFormat:#"self CONTAINS[CD] %#",yourStringValue];
NSArray *ar=[names filteredArrayUsingPredicate:pd];
NSLog(#"%#",ar);
Output:-
"Aaron David"
I'm trying to find all instances of an object that contain a reference to a combination of separate objects in my object graph.
recommendation
may contain one or more of the following three objects:
damageType
areaDamaged
validVehicles
This structure is built from an import of an existing system's file format and I am unable to restructure the object graph.
I'm using an NSPredicate to find all recommendation objects that have a damageType matching a selected damage as follows:
NSFetchRequest *fetchRequestDamages = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([Recommendation class])];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"ANY damageType == %#", _currentRecordedDamage.damageType];
But want the filter to return all Recommendations that have matches for a specific damageType, areaDamaged and validVehicle
I've tried
NSMutableArray *predicates = [[NSMutableArray alloc] initWithCapacity:2];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"ANY damageType == %#", _currentRecordedDamage.damageType];
[predicates addObject:predicate];
NSPredicate *predicate2 = [NSPredicate predicateWithFormat:#"ANY areaDamaged == %#", _currentAreaDamaged];
[predicates addObject:predicate2];
NSPredicate *predicate3 = [NSPredicate predicateWithFormat:#"ANY validVehicles == %#", _currentVehicle];
[predicates addObject:predicate3];
fetchRequestDamages.predicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicates];
fetchRequestDamages.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES]];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequestDamages managedObjectContext:[RKManagedObjectStore defaultStore].mainQueueManagedObjectContext sectionNameKeyPath:nil cacheName:nil];
self.fetchedResultsController.delegate = self;
NSError *error;
[self.fetchedResultsController performFetch:&error];
int resultsFound = self.fetchedResultsController.fetchedObjects.count;
but it seems this returns the set of all objects satisfying any of the predicates - I'd like the set of objects that match all three.
I'm looking into using SUBQUERY but can't quite make sense of how to create this query?
Just combine the three predicates with "AND" to find the objects that match all of them:
NSArray *predicates = ... // your array of predicates
NSPredicate *finalPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicates];
[fetchRequestDamages setPredicate:finalPredicate];
Why not to use AND in one query?
Something like:
damage = %# AND damagePoints = %# AND damageCost = %#
and:
damageType IN %#
Where %# in the last code example should be an array/set or something else.
Im using coredata in my app,
I can search all entities with a starting letter,
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name MATCHES '^[hH].*'"];
//sort descriptor!
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES selector:#selector(localizedCaseInsensitiveCompare:)];
NSArray *companyProducts = [Company allWithPredicate:predicate sortDescriptors:#[sortDescriptor]];
Company *theCompany;
NSLog(#"tus companies number:: %d", companyProducts.count);
for (theCompany in companyProducts) {
NSLog(#"tus companies:: %#", theCompany.name);
}
so in this case I will get all companies starting with h no matter lower or upper case...
but if I need to search for matches with more than one letter? no matter lower or upper case,
for example to look for:
Hyper
hyosung
So I need to know how to construct my regex? to have a search for n number of charaters on my properties?
Thanks!
Try with
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name BEGINSWITH [c] %#",#"H"];
Boundary <--> Datasets <-->> DataA
I want to find all Entities of DataA that belong to Boundary boundary1;
I tried:
NSPredicate *predication = [NSPredicate predicateWithFormant:#"datasets.boundary.boundaryID == %#", myBoundaryID];
but it has issue when trying to find the Boundary's properties.
My other thought was:
NSArray *savedAnalysis = [NSArray arrayWithArray:[dataset.savedAnalysis allObjects]];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:NAME ascending:TRUE];
NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor];
self.datasourceSavedAnalysis = [NSArray arrayWithArray:[savedAnalysis sortedArrayUsingDescriptors:descriptors]];
But I don't know how to sort the Core Data Entities in the array.
I am not a database guy and I'm having trouble figuring out the logic to this stuff.
Try the following:
NSPredicate *predication = [NSPredicate predicateWithFormant:#"datasets.boundary == %#", myBoundary];
wWhere myBoundary is a Boundary entity.
Hey i want to filter an NSArray. In this Array is a lot of information like name, town, telephonenumber, and so on. But some towns are twice or three times in the array.
I have property with a town in it.
So i want only those objects from the arry which match with the property.
For example:
in the Array stands:
Frank, New York, 123456
Oliver, New York, 123456
Thomas, Boston, 123456
and when the property is New York i want olny objects 1 and 2.
Does anyone has an idea how i can do it?
This is my code:
NSString *filterString = newsArticle;
NSPredicate *prediacte = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"Ort == '%#'",filterString]];
newsTownArray = [news filteredArrayUsingPredicate:predicate];
and when i come to the line:
cell.textLabel.text=[[newsTownArray objectAtIndex:indexPath.row] objectForKey:"Name"];
You need to use NSPredicate for this.
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"town == 'New York'"];
[yourArray filterUsingPredicate:predicate];
Dynamically you can create predicate like:
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"town == '%#'",yourInput]];
Here yourInput is a NSString which holds the required town name.
Please check these articles for more details:
codeproject
useyourloaf
Use this code
NSMutableArray *subpredicates = [NSMutableArray array];
for(NSString *term in arryOfWordsToBeSearched) {
NSPredicate *p = [NSPredicate predicateWithFormat:#"self contains[cd] %#",term];
[subpredicates addObject:p];
}
NSPredicate *filter = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
result = (NSMutableArray*)[arryOfDummyData filteredArrayUsingPredicate: filter];
However you can do it within an array with the use of NSPredicate, but I will suggest to do bit differently, this will add up to your code and good programming way.
Create a custom class Person having these properties name, city and telephone.
Create an array that will store objects of Person.
After this you can manipulate/ filter / sort etc quite easily.
NSString *filterCity=#"Delhi";
NSMutableArray *yourArray=[NSMutableArray arrayWithArray:self.persons];
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"city == '%#'",filterCity]];
[yourArray filterUsingPredicate:predicate];
NSLog(#"Filtered");
for (Person *per in yourArray) {
NSLog(#"Name: %#, City: %#, Telephone: %#",per.name, per.city, per.telephone);
}