问题描述
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
[self.map removeAnnotations:self.map.annotations];
if ([textField isEqual:self.searchText]) {
NSPredicate *bPredicate =
[NSPredicate predicateWithFormat:@"name contains[c], %@",self.searchText.text];
self.filteredArray = [self.hotelArray filteredArrayUsingPredicate:bPredicate];
NSLog(@" HEARE %@",self.filteredArray);
[self markAllHotels];
}
return YES;
}
hotelArray
和 filteredArray
是 NSArray
s。
hotelArray
的对象类型为 hotel
其中 hotel
有一个属性姓名
。
hotelArray
has objects of type hotel
where hotel
has a property name
.
问题:
我想过滤 hotelArray
根据到 hotel.name
当 hotel.name
匹配在 searchText中输入的文字
[text field],但我得到一个空的 self.filteredArray
。
Problem :I want to filter hotelArray
according to hotel.name
when hotel.name
matches text entered in searchText
[text field], but I am getting an empty self.filteredArray
.
推荐答案
尝试以下行,并确保 properyName
区分大小写。并且你已经以谓词格式放置了,
,这就是为什么它无法正常工作。只需用以下代码替换您的代码。
Try following lines, and make sure properyName
is case sensitive. and you have placed ,
in predicate format, thats why its not working. just replace your code with following.
目标C
NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"SELF.name contains[cd] %@",self.searchText.text];
self.filteredArray = [self.hotelArray filteredArrayUsingPredicate:bPredicate];
NSLog(@"HERE %@",self.filteredArray);
Swift
var bPredicate: NSPredicate = NSPredicate(format: "SELF.name contains[cd] %@", self.searchText.text)
self.filteredArray = self.hotelArray.filteredArrayUsingPredicate(bPredicate)
NSLog("HERE %@", self.filteredArray)
使用swift 过滤器
Using swift filter
var searchText = "Galaxy"
let filteredArray = hotelArray.filter { $0["name"] == searchText }
print("** Result ** \n\(filteredArray)")
Swift 3.0
let arrEmp = [["name": "James", "age" : 27, "city" : "New york"],
["name": "Johnson", "age" : 24, "city" : "London"],
["name": "Alex", "age" : 28, "city" : "Newark"],
["name": "Mark", "age" : 25, "city" : "Paris"],
["name": "Steve", "age" : 25, "city" : "Silicon Valley"],
["name": "Lary", "age" : 28, "city" : "New york"]]
// *** Filter by Name exact match ***
var filterByName = arrEmp.filter { $0["name"] == "Mark" }
print("filterByName \(filterByName)")
// *** Filter by Age ***
var filterByAge = arrEmp.filter { $0["age"] as! Int > 25 }
print("filterByAge \(filterByAge)")
Swift 4.0
var filterByName = arrEmp.filter
do {
$0["name"] == "Mark"
}
print("filterByName filterByName)")
var filterByAge = arrEmp.filter
do {
$0["age"] as! Int > 25
}
print("filterByAge filterByAge)")
这篇关于如何使用对象属性的谓词过滤NSArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!