I want to perform a search on an entity I have (using realm-cocoa
) For example:
@interface Person : RLMObject
@property NSString *firstName;
@property NSString *lastName;
@property NSString *nickName;
@end
I have a UIViewController
that holds a UITableView
that is displaying a list of all the Person
entities, I also have a UISearchBar
above the table.
Now, What I want is when a user enters certain text in the search bar, to search if this text is contained in any of my properties , also, I want to sort the results based on relevance.
For example, if have have a person named Sandro and another named Alessandro, when i'm searching for the text 'Sandro' I want to see the person named Sandro first, if i search 'San' I want to sort alphabetically (meaning Alessandro will be first).
I have not found a method in realm
that can help me achieve this.
In Objective-C
you need to declare a RLMResult
object to get the array of Person objects and using the sortedResultUsingKeyPath
method you can sort your result
Try with this
In Objective-C
RLMRealm * realm = [RLMRealm defaultRealm];
[realm transactionWithBlock:^{
[realm addObject:[Person personWithFirstName:@"Reinier"]];
[realm addObject:[Person personWithFirstName:@"Test"]];
}];
NSString * searchValue = @"Re";
//Here we search for objects that containts in the firstName the value of searchValue string
RLMResults * result2 = [[Person objectsWithPredicate:[NSPredicate predicateWithFormat:@"firstName CONTAINS %@",searchValue]] sortedResultsUsingKeyPath:@"firstName" ascending:true];
NSMutableArray * arrayOfPerson = [NSMutableArray array];
for (int i = 0; i< [result2 count];i++)
{
[arrayOfPerson addObject:[result2 objectAtIndex:i]];
}
NSLog(@"%@",arrayOfPerson);
this is in Swift
yourArrayOfPersons = realm?.objects(Person.self).sorted(byKeyPath: "firstName")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.