简体   繁体   English

predicateWithFormat NSMutableArray问题

[英]predicateWithFormat NSMutableArray Issue

I have an error with predicateWithFormat causing a crash in my app. 我的predicateWithFormat错误导致我的应用程序崩溃。

The problematic code is: 有问题的代码是:

@implementation SecondViewController
{
NSArray *searchResults;
}

@synthesize jsonConnection, bakeryProductArray, bakeryTableView;

- (void)viewDidLoad
{
[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.
[self retrieveData];
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

#pragma mark - UITableView DataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
    return [searchResults count];
}
else {
return [bakeryProductArray count];

}
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath     *)indexPath
{
static NSString *cellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle   reuseIdentifier:cellIdentifier];
}

if (tableView == self.searchDisplayController.searchResultsTableView) {
    cell.textLabel.text = [searchResults objectAtIndex:indexPath.row];
}
else {
foodProducts *currentProduct = [bakeryProductArray objectAtIndex:indexPath.row];
cell.textLabel.text = currentProduct.productName;
cell.detailTextLabel.text = currentProduct.productName;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

return cell;

}

#pragma mark - UITableView Delegate methods

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (bakeryTableView == self.searchDisplayController.searchResultsTableView) {
    [self performSegueWithIdentifier: @"bakeryDetails" sender: self];
}

    detailedViewController *productinfo = [self.storyboard instantiateViewControllerWithIdentifier:@"bakeryDetails"];
    //Retrieve current user array
    foodProducts *currentProduct2 = [bakeryProductArray objectAtIndex:indexPath.row];
    productinfo.productName = currentProduct2.productName;
    productinfo.productImage = currentProduct2.productImgUrl;
    productinfo.productDescription = currentProduct2.productDescription;
    productinfo.productPrice = currentProduct2.productPrice;
    productinfo.productQuantity = currentProduct2.productquantity;
    productinfo.productAllergy = currentProduct2.productAllergy;

    [self.navigationController pushViewController:productinfo animated:YES];
    [bakeryTableView deselectRowAtIndexPath:indexPath animated:YES];
}


//Becareful here as wrong predicateWithFormat can crash app on keying in search 
-(void)filterContentForSearchText:(NSString *)searchText scope:(NSString *)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithBlock:^BOOL(NSString * testString,    NSDictionary *bindings) {
    return ([searchText compare:testString options: NSCaseInsensitiveSearch] == NSOrderedSame);
}];

searchResults = [bakeryProductArray filteredArrayUsingPredicate:resultPredicate];
}


-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
                           scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                  objectAtIndex:[self.searchDisplayController.searchBar
                                                 selectedScopeButtonIndex]]];

return YES;
}


#pragma mark - methods

-(void) retrieveData
{
NSURL *url = [NSURL URLWithString:getDataUrl];
NSData *data = [NSData dataWithContentsOfURL:url];

jsonConnection = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
bakeryProductArray = [[NSMutableArray alloc]init];

for (int i = 0; i < jsonConnection.count; i++)
{
    NSString *pID = [[jsonConnection objectAtIndex:i] objectForKey:@"id"];
    NSString *pName = [[jsonConnection objectAtIndex:i] objectForKey:@"Name"];
    NSString *pImageUrl = [[jsonConnection objectAtIndex:i] objectForKey:@"ImageUrl"];
    NSString *pDescription = [[jsonConnection objectAtIndex:i] objectForKey:@"Description"];
    NSString *pQuantity = [[jsonConnection objectAtIndex:i] objectForKey:@"Quantity"];
    NSString *pPrice = [[jsonConnection objectAtIndex:i] objectForKey:@"Price"];
    NSString *pAllergy = [[jsonConnection objectAtIndex:i] objectForKey:@"Allergy"];

    foodProducts *myProducts = [[foodProducts alloc]initWithproductID:pID andproductName:pName andproductImgUrl:pImageUrl andproductDescription:pDescription andproductquantity:pQuantity andproductPrice:pPrice andproductAllergy:pAllergy];


    [bakeryProductArray addObject:myProducts];
}


[self.bakeryTableView reloadData];

}

FoodProduct class 食品类

@implementation foodProducts
@synthesize productID, productName, productImgUrl, productquantity,productDescription, productPrice, productAllergy;

-(id) initWithproductID:(NSString *)uproductID andproductName:(NSString *)uproductName andproductImgUrl:(NSString *)uproductImage andproductDescription:(NSString *)uproductDescription andproductquantity:(NSString *)uproductquantity andproductPrice:(NSString *)uproductPrice andproductAllergy:(NSString *)uproductAllergy
{
self = [super init];
if  (self)
{
    productID = uproductID;
    productName = uproductName;
    productImgUrl = uproductImage;
    productquantity = uproductquantity;
    productDescription = uproductDescription;
    productPrice = uproductPrice;
    productAllergy = uproductAllergy;

}
return self;
}

The array which is being fed into the NSPredicate is @property (nonatomic, strong) NSMutableArray *bakeryProductArray; 送入NSPredicate的数组是@property @property (nonatomic, strong) NSMutableArray *bakeryProductArray;

Error says: Can't use in/contains operator with collection 错误提示:无法在集合中使用in / contains运算符

Any ideas, on whats going wrong? 有什么想法,怎么了?

Your array does not contain strings , but custom foodProducts objects. 您的数组不包含字符串 ,而是自定义foodProducts对象。

To filter the objects by "product name", you would use 要通过“产品名称”过滤对象,您可以使用

[NSPredicate predicateWithFormat:@"productName CONTAINS[cd] %@", searchText];

ADDED: There is another error in your code: 添加:您的代码中还有另一个错误:

cell.textLabel.text = [searchResults objectAtIndex:indexPath.row];

cannot work because the right-hand side does not return a string. 无法使用,因为右侧不返回字符串。 It should be 它应该是

foodProducts *currentProduct = [searchResults objectAtIndex:indexPath.row];
cell.textLabel.text = currentProduct.productName;

NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"self.productName contains[cd] %@", searchText]; NSPredicate * resultPredicate = [NSPredicate predicateWithFormat:@“ self.productName contains [cd]%@”,searchText];

NSArray *searchResults = [self.bakeryProductArray filteredArrayUsingPredicate:resultPredicate]; NSArray * searchResults = [self.bakeryProductArrayfilteredArrayUsingPredicate:resultPredicate];

NSLog(@"%@",searchResults); NSLog(@“%@”,searchResults);

If above doesn't work can you show your foodProduct class (model). 如果上述方法不起作用,您可以显示foodProduct类(模型)。

Ideally you should use like[cd] instead of contains[cd]. 理想情况下,您应该使用like [cd]而不是contains [cd]。

Refer: http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/Predicates/Articles/pSyntax.html 1 CONTAINS The left-hand expression contains the right-hand expression. 请参阅: http : //developer.apple.com/library/ios/#documentation/cocoa/conceptual/Predicates/Articles/pSyntax.html 1包含内容左侧表达式包含右侧表达式。

2 LIKE The left hand expression equals the right-hand expression: ? 2 LIKE左手表达式等于右手表达式:? and * are allowed as wildcard characters, where ? 和*允许用作通配符,其中? matches 1 character and * matches 0 or more characters. 匹配1个字符,*匹配0个或更多字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM