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

标签 ios iphone objective-c

-(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/

相关文章:

ios - 使用 ALAssetLibrary 保存到相册时失败

iphone - 增加对 scrollViewDidScrollToTop 的计数

ios - 实现动态内容的透明模糊导航栏

iphone - 保持 iPhone UIButton 突出显示

ios - UICollectionview 加载单元格时滚动不连贯

iOS 在 UIGraphicsBeginPDFPageWithInfo 内崩溃

iphone - 我怎样才能改变 UITextview 的内容

iphone - 检查值是否为整数(Objective-C)

ios - Swift:找不到 AVCaptureStillImageOutput 的连接

ios - 尝试在表格 View 中按日期对核心数据对象进行排序