Realm not query string field with whitespace

北城以北 提交于 2019-12-12 04:55:26

问题


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
}

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?


回答1:


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.

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:

  • Use CONTAINS to find any objects whose foodType properties contains the given type 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.



来源:https://stackoverflow.com/questions/45825620/realm-not-query-string-field-with-whitespace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!