gpt4 book ai didi

ios - 如何使用对象属性上的谓词过滤 NSArray

转载 作者:IT王子 更新时间:2023-10-29 07:48:13 27 4
gpt4 key购买 nike

-(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;
}

hotelArrayfilteredArrayNSArray

hotelArray 具有 hotel 类型的对象,其中 hotel 具有属性 name

问题:当 hotel.name 匹配在 searchText [文本字段中输入的文本时,我想根据 hotel.name 过滤 hotelArray ],但我得到一个空的 self.filteredArray

最佳答案

尝试以下几行,并确保 properyName 区分大小写。并且您已将 , 置于谓词格式中,这就是它不起作用的原因。只需将您的代码替换为以下即可。

Objective-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 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)")

关于ios - 如何使用对象属性上的谓词过滤 NSArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19676371/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com