Fetch Realm objects that contain parameter - ios

I have a realm database filled with Restaurant objects that have a url parameter. I'd like to fetch the objects where the url contains what the user has typed in a UITextField.
NSPredicate *pred = [NSPredicate predicateWithFormat:#"url CONTAINS '%#'", self.searchQuery];
RLMResults<Database *> *results = [Database objectsWithPredicate:pred];
if ([results count] == 0) {
NSLog(#"results count == 0");
return nil;
}
Now, when I run this, I always get 0 results. Eventhough I have two example entries that have 'http://www.testingthis.com' as an url and the search query is 'testingthis'. Any ideas as to why I'm not getting results?

You need to perform your search query against the Restaurant class itself; not Database. Realm uses the class you specify to determine which table in which to apply the query.
As an aside, you can also inline NSPredicate queries with +[RLMObject objectsWhere:], so it's not necessary to create a separate NSPredicate object (unless you've got a specific reason). :)
RLMResults *restaurants = [Restaurant objectsWhere:#"url CONTAINS '%#'", #"testingthis"];
If you're trying to query for Restaurant objects that aren't in the default Realm, then you can alternatively use +[RLMObject objectsInRealm: where:] to explicitly control which database you're querying.

Related

Core Data, Get Sum Of Certain Boolean Value Attribute

I'm logging a Core Data attribute "passed" (Boolean value)
for (Circuit *object in self.distributionBoard.circuits) {
NSLog(#"Core Data Value = %d", object.passed);
}
This logs fine. What's the most efficient way to count the number of times the saved boolean value == 1?
Using NSFetchReques or NSExpression did not yield the desired result so far. Looked here: Core Data sum of all instances attribute and similar, with the usual searches
Since your property is a boolean, you can make it a lot simpler than the methods described in that answer. Use a predicate to match the value of passed and then get the count of the result instead of the fetched objects. Something like:
NSFetchRequest<Event *> *fetchRequest = MyEntity.fetchRequest;
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"passed = true"];
NSError *error = nil;
NSUInteger count = [self.managedObjectContext countForFetchRequest:fetchRequest error:&error];
Then count has the number of instances where passed is true.

IOS/Objective-C: Search string element with array of objects

As part of an autocomplete box, I am searching names within an array of contacts. However, after the user picks a name from the suggested List, I need to grab the id of the contact which is in the array of contact objects but not the array of names that appear in the suggest box. I've been working with just the names as that's what I want to display in the suggestion box but have an array of contacts as well.
How would I convert code below (probably using key values) to search the name dimensions of an array of objects instead of an array of names so as to keep track of the ids of the objects. I am kind of fuzzy on arrays and key values.
//the array being searched looks something like #[#"John", #"Dave", #"Sam", #"Xian", #"Ahmed", #"Johann"];
//I want to search the names in an array that looks something like:
(
{
first = "John";cid = 2;},
{
first = "Dave";cid = 44;},
{
first = "Xian";cid=99})
//this code works great to search names but I lose track ids. Thank you for any suggestions.
-(void)searchArray: (NSMutableArray*) array forString: (NSString *) term {
[_contactsSuggested removeAllObjects];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains[c] %#",term];
NSArray *tempArray = [array filteredArrayUsingPredicate:predicate];
_contactsSuggested = [NSMutableArray arrayWithArray:tempArray];
[_autocompleteTableView reloadData];
}
Create a Contact object. Give it a name property, an id property, and any other properties you need. Then write code that searches an array of Contact objects rather than just an array of names. You could then create a predicate using predicateWithBlock to filter the items that match your name property.

Getting distinct rows from Realm table in iOS

I am using Realm database for iOS application where i have a use case in which i want to filter result set by distinct values for a particular field. This field is not a primary key of the realm table.
I was not able to construct query for that.
Sample query :
RLMResults *allFiles = [FileRLMObject objectsInRealm:realmObject where:#"colA == %#", #"test1"];
FileRLMObject is a subclass of RLMObject from realm library
here table contains one column with name colB. While getting allFiles results, i want to get rows which are having distinct colB values.
Any suggestions how i can achieve this?
Realm doesn't support distinct queries yet. You can subscribe issue #1103 to track progress on that.
As a workaround, you could query for all values for colB first and then select objects for each value of it, as seen below:
NSArray *values = [FileRLMObject.allObjects valueForKey:"type"];
NSSet *distinctValues = [NSSet setWithArray:values];
NSMutableArray *allFiles = [NSMutableArray new];
for (NSString *colB in distinctValues) {
// This takes the firstObject.
// You might want to modify the sort order to make sure
// you get a certain object in case that there may exist
// multiple objects per distinct value.
FileRLMObject *object = [FileRLMObject objectsWhere:#"colB == ?", colB].firstObject;
[allFiles appendObject:object];
}

Core Data Fetch Results Reduced Set of Related Items

I have a NSFetchResult that returns managed objects that contain MANY related objects ( Aobj ->> Bobj). The "Bobj" managed object contains a BOOL attribute "isSet" (stored as NSNumber). The NSFetchResult returns all Aobj objects.
I would like a suggestion for an NSPredicate that would return an Aobj with only those Bojs where isSet is TRUE (#1).
Currently, I enumerate over my NSArray of Aobjs returned by my fetch result so that I can get my filtered NSArray of Aobjs this way:
- (NSArray *)filteredObject:(Aobj *)aObj
{
NSMutableArray* bObjs = [aObj.bObjs mutableCopy];
[bObjs enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(Bobj* bObj, NSUInteger idx, BOOL *stop)
{
if (bObj.isSet == [NSNumber numberWithBool:NO])
{
[bObjs removeObject:story];
}
}];
return bObjs;
}
Asked another way: how would I define an NSPredicate for my NSFetchResult that would get all my Aobjs but limit the related Bobjs to those matching Bobj.isSet == YES?
Thanks in advance!
NSPredicate *myPredicate = [NSPredicate predicateWithFormat:#"SELF.bObjs.isSet == YES"];
[myFetchRequest setPredicate:myPredicate];
NSArray *array = [moc executeFetchRequest:myFetchRequest error:&error];
Use a subquery. Subqueries follow this general format:
SUBQUERY(relationship, related_thing, predicate)
relationship is the relationship on the object being evaluated.
related_thing is an individual object in the relationship. It's prefixed by a $ and is then used in the predicate (not shown above, for clarity).
predicate is the predicate to apply to related_thing.
With your example, it would look like (assuming your relationship is called 'bobjs'):
SUBQUERY(bobjs, $obj, $obj.isSet == YES)
Subqueries can be quite powerful. For example, you can also apply collection operators to the subquery:
SUBQUERY(bobjs, $obj, $obj.isSet == YES).#count > 1 would give you each AObj that has at least one object in the 'bobjs' relationship with isSet equal to YES. Obviously, you can use other collections operators or layer logical operations or additional expressions on top of this.

Deleting objects from Core Data that doesn't exist in an array

I have a Core Data object like the following.
DummyObject
{
objectID:<objectID>
objectName:<objectName>
}
And I have 1000 of these DummyObjects saved. I have also an array objectArray which contains 100 of these DummyObjects.
I want to run a query that would delete all the DummyObjects which are not in this array.
From my comment
You could just try a predicate like the following for your fetch request
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"NOT (self IN %#)", yourArray];
Using it together with a NSFetchRequest allows you to retrieve the objects that are not in the array.
Obviously, yourArray contains objects of type DummyObject.
To delete,
// fetch request with predicate...
NSArray* results = // execute the fetch request
for(NSManagedObject* dummy in results) {
[context deleteObject:dummy];
}
// save here...
where results is the array of objects retrieved by your fetch request.

Resources