簡體   English   中英

iOS領域中的高級搜索

[英]Advanced search in realm iOS

我想對我擁有的實體執行搜索(使用realm-cocoa ),例如:

@interface Person : RLMObject
@property NSString *firstName;
@property NSString *lastName;
@property NSString *nickName;
@end

我有一個UIViewController ,它包含一個UITableView ,該UITableView顯示所有Person實體的列表,在表上方也有一個UISearchBar

現在,我想要的是當用戶在搜索欄中輸入某些文本時,要搜索該文本是否包含在我的任何屬性中 ,而且,我想根據相關性對結果進行排序。

例如,如果有一個叫Sandro的人和另一個叫Alessandro的人,當我搜索文本“ Sandro”時,我想首先看到一個叫Sandro的人,如果我搜索“ San”,我想按字母順序排序(表示Alessandro將是第一個)。

我沒有找到一個方法realm ,可以幫助我實現這一目標。

Objective-C您需要聲明一個RLMResult對象以獲取Person對象的數組,並使用sortedResultUsingKeyPath方法可以對結果進行排序

試試這個

在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);

這是在斯威夫特

yourArrayOfPersons = realm?.objects(Person.self).sorted(byKeyPath: "firstName")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM