如何从NSObject数组过滤项目

时间:2019-04-29 11:29:03

标签: swift uitableview filter uisearchbar

下面是我的2个对象

肌肉

struct MuscleListObject {
    var strMuscleName: String = ""
    var arrMuscleExercise: [MuscleExerciseListObject] = []
}

ExerciseObject

struct MuscleExerciseListObject {
    var strExerciseName: String  = ""
}

我知道肌肉明智的过滤器,但我想搜索运动明智的项目。我怎样才能做到这一点?请为此指导我。

arrSearchedMuscle = self.arrExercise.filter({ objMuscle in
    if let name = objMuscle.strMuscleName as? String, let query = searchBar.text {
        return name.range(of: query, options: [.caseInsensitive, .diacriticInsensitive]) != nil
    }
    return false
})

编辑

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchText.count == 0 {
            isSearching = false
            arrSearchedMuscle = arrExercise
        }
        else {
            isSearching = true

            let query = searchText
            arrSearchedMuscle = arrExercise.compactMap { category -> MuscleListObject? in
                if category.strMuscleName.range(of: query, options: [.caseInsensitive]) != nil {
                    return category
                } else {
                    arrSearchedExercise = category.arrMuscleExercise.filter({ $0.strExerciseName.range(of: query, options: [.caseInsensitive]) != nil  })
                    if arrSearchedExercise.isEmpty {
                        return nil
                    } else {
                        let newCategory = category
                        newCategory.arrMuscleExercise = arrSearchedExercise
                        return newCategory
                    }
                }
            }
            print(arrExercise)
            print(arrSearchedMuscle)
        }
        self.tblVWExercise.reloadData()
    }

请指导我有关过滤器调用的信息。 预先感谢

1 个答案:

答案 0 :(得分:1)

如果Muscle标题包含搜索查询,则返回整个Muscle对象。如果没有,则用搜索查询过滤运动对象并返回更新的肌肉对象。如果特定的Muscle对象不包含搜索查询,则返回nil

let query = "band"
arrSearchedMuscle = arrExercise.compactMap { category -> MuscleListObject? in
    if category.strMuscleName.range(of: query, options: [.caseInsensitive]) != nil {
        return category
    } else {
        let filteredItems = category.arrMuscleExercise.filter({ $0.strExerciseName.range(of: query, options: [.caseInsensitive]) != nil  })
        if filteredItems.isEmpty {
            return nil
        } else {
            var newCategory = category
            newCategory.arrMuscleExercise = filteredItems
            return newCategory
        }
    }
}
print(arrExercise)
print(arrSearchedMuscle)

enter image description here