领域不使用空格查询字符串字段 [英] Realm not query string field with whitespace

查看:58
本文介绍了领域不使用空格查询字符串字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据源中有这样的功能:

I have such function in my data source:

func getAllFood(by type: String) -> [UserFoodInformation] {
    var findedFood = [UserFoodInformation]()
    findedFood.append(contentsOf: baseUserFoodDataSource.getAllFood(by: type))
    let predicate = NSPredicate(format: "foodType == %@", type)
    let resultOfSearching = dataBase.objects(AddedUserFood.self).filter(predicate).sorted(byKeyPath: "name")
    for searchedFood in resultOfSearching {
        findedFood.append(searchedFood)
    }
    return findedFood
}

当我尝试使用包含空格的字符串进行查询时,没有任何结果,但是如果我使用简单的一字参数进行查询,一切都会很好.这是为什么?我可以在Realm中有一个包含多个单词的字符串字段吗?

When I try to query with string that consist whitespace, I have no result, but if I query with simple one-word parameter, everything goes fine. Why is that? Can I have a string field in Realm that consists multiple words?

推荐答案

您使用的谓词正在查找其foodType属性等于传入的type字符串的对象.仅那些其属性的对象完全等于该字符串将匹配.如果要执行其他形式的匹配,则需要使用除等于运算符以外的其他方式. BEGINSWITHCONTAINSENDSWITHLIKE是Realm在字符串字段上支持的比较运算符.

The predicate you're using is looking for objects whose foodType property is equal to the type string that is passed in. Only those objects whose property is exactly equal to that string will match. If you want to perform some other form of matching you'll need to use something other than the equality operator. BEGINSWITH, CONTAINS, ENDSWITH and LIKE are the comparison operators that Realm supports on string fields.

我可以在Realm中有一个由多个单词组成的字符串字段吗?

Can I have a string field in Realm that consists multiple words?

字符串字段可以包含任何字符串值.但是,受支持的比较运算符没有单词"的概念,因此,如果您要使用该概念进行过滤,则可能需要进一步进行工作.根据您的用例,我可以看到几种解决方法:

String fields can contain any string values. The supported comparison operators don't have the concept of a "word", though, so if you want to do filtering using that concept you'll likely need to do further work on your part. Depending on your use case, I can see a couple of ways to go about it:

  • 使用CONTAINS查找其foodType属性包含给定的type字符串的所有对象.

  • Use CONTAINS to find any objects whose foodType properties contains the given type string.

将字符串解析为存储在模型中的结构化数据.例如,为foodType属性存储List<FoodType>而不是String可能很有意义.

Parse the string into structured data that you store in your model. For instance, it may make sense to store a List<FoodType> rather than a String for the foodType property.

可能还有其他选择,但是它们取决于您要实现的目的的细节,以实现您尚未共享的东西.

There are likely other options, but they depend on details of what it is you're trying to achieve that you've not shared.

这篇关于领域不使用空格查询字符串字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆