suitsArray是 MutableArray,在按钮处于选中状态时添加了对象(单词)。
在接下来的部分中,我需要将suitsCriteriaString 设置为一个干净的字符串,其中单词与 suitsArray 之间只有一个空格,这意味着没有逗号或其他符号!(用 NSSet 什么的?)
NSString *suitsCriteriaString = [NSString stringWithFormat:@"%@", suitsArray];
NSString *wineSuitsString = [wine objectForKey:@"Suits"];
NSRange range = [wineSuitsString rangeOfString:suitsCriteriaString options:NSCaseInsensitiveSearch];
然后,如果操作正确,NSRange 应该检查 suitsCriteriaString 中的单词是否存在于wineSuitsString中。然后,结果应该被过滤为只包含匹配的单词!
我的搜索功能的代码如下,如果您需要更多信息来完成这项工作,请告诉我。
SearchViewController.h
#import <UIKit/UIKit.h>
@interface SearchViewController : UIViewController {
@property (nonatomic, strong) NSMutableArray *allObjectsArray;
@property (nonatomic, strong) NSMutableArray *resultObjectsArray;
@property (nonatomic, strong) NSMutableArray *suitsArray;
@property (nonatomic, retain) IBOutlet UISlider *minPrisSlider;
@property (nonatomic, retain) IBOutlet UISlider *maxPrisSlider;
-(IBAction)searchButtonPressed:(id)sender;
@end
SearchViewController.m:
填充所有对象数组:
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Wine.plist"];
allObjectsArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
}
从 suitsArray 添加或删除对象,我有 10 个类似于此的按钮:
-(IBAction)lambButtonPressed:(id)sender
{
if (lambButtonSelected == 0) {
lambButtonSelected = 1;
[suitsArray addObject:@"lamb"];
} else {
lambButtonSelected = 0;
[suitsArray removeObject:@"lamb"];
}
}
然后,将对象添加到搜索结果:
-(IBAction)searchButtonPressed:(id)sender{
resultObjectsArray = [NSMutableArray array];
for(NSDictionary *wine in allObjectsArray)
{
//String for price
NSString *winePrice = [wine objectForKey:@"Price"];
/*THIS IS WHERE I'M TRYING TO CHECK IF THE WORDS IN suitsCriteriaString
ARE EXISTING IN wineSuitsString */
NSString *suitsCriteriaString = [NSString stringWithFormat:@"%@", suitsArray];
NSString *wineSuitsString = [wine objectForKey:@"Suits"];
NSRange range = [wineSuitsString rangeOfString:suitsCriteriaString options:NSCaseInsensitiveSearch];
//THEN LAST, ADD OBJECTS WITH MATCH OF PRICE CRITERIA AND SUITS CRITERIA TO RESULTS:
BOOL priceConditionGood = YES;
if (minPrisSlider.value <= maxPrisSlider.value && (winePrice.floatValue < minPrisSlider.value || winePrice.floatValue > maxPrisSlider.value))
priceConditionGood = NO;
if (range.location != NSNotFound && priceConditionGood)
[resultObjectsArray addObject:wine];
}
}
//AND PUSH RESULTS CONTROLLER:
ResultsTableViewController *nextController = [[self storyboard] instantiateViewControllerWithIdentifier:@"ResultsController"];
nextController.objectsArray = [[NSMutableArray alloc]initWithArray:resultObjectsArray];
[self.navigationController pushViewController:nextController animated:YES];
}