如何比较每个字典中 JSON Array 键值的字符串以查看它们是不是包含 NSUserDefault 字符串并返回 JSON 字典匹配项

Posted

技术标签:

【中文标题】如何比较每个字典中 JSON Array 键值的字符串以查看它们是不是包含 NSUserDefault 字符串并返回 JSON 字典匹配项【英文标题】:How to compare JSON Array key value's strings in each dictionary to see if they contain NSUserDefault strings and return JSON Dictionary matches如何比较每个字典中 JSON Array 键值的字符串以查看它们是否包含 NSUserDefault 字符串并返回 JSON 字典匹配项 【发布时间】:2016-08-28 20:26:58 【问题描述】:

我是初学者,这个主题对我来说很难理解。任何代码帮助将不胜感激。

主 UITableView 包含来自本地 JSON 文件的所有配方对象。

第二个 UITableView 包含 JSON 文件中每个配方的所有成分值,用户可以在其中选择成分。在第二个表格视图中,我使用了 replaceOccurrencesOfString 来缩短成分字符串,例如,从 1/2 汤匙盐。选定的成分存储在 NSUserDefaults 中。

我需要能够过滤显示在主 tableview 上的食谱,以仅显示那些包含用户在第二个 tableview 中选择的成分的食谱。由于在第二个表视图中使用了 replaceOccurrencesOfString,存储在 NSUserDefaults 中的成分不能与 JSON 文件中的成分完全匹配。

有人对如何做到这一点有任何建议吗?我什至不知道从哪里开始。

本地 JSON 文件:


      "locations": [

     "name" : "Drop Biscuits and Sausage Gravy", "ingredients" : "Biscuits\n3 cups All-purpose Flour\n2 Tablespoons Baking Powder\n1/2 teaspoon Salt\nShortened for example”, "cookTime" : "PT30M" ,

     "name" : "Hot Roast Beef Sandwiches", "ingredients" : "12 whole Dinner Rolls Or Small Sandwich Buns (I Used Whole Wheat)\n1 pound Thinly Shaved Roast Beef Or Ham (or Both!)\nShortened for example”, "cookTime" : "PT30M" ,  
    //many more records.  only included 2 for example                            
      ]
    

主表视图 - 所有食谱都在 UITableView 中返回,如下所示:

@interface LocationsViewController () <UISearchResultsUpdating>

@property (nonatomic, strong) NSArray *RecipeArray;
@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) NSMutableArray *searchResults;
@property (nonatomic, strong) NSArray *RecipeByIngredientsArray;

@end

@implementation LocationsViewController 
    NSArray *_locations;




- (void)viewDidLoad 
    [super viewDidLoad];


initWithTitle:(@"Kitchen") style:(UIBarButtonItemStylePlain) target:(self) action:(@selector(FilterButton:))];



    // Create a new JSONLoader with a local file URL
    JSONLoader *jsonLoader = [[JSONLoader alloc] init];
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"locations" withExtension:@"json"];

    instantiateViewControllerWithIdentifier: method
    UINavigationController *searchResultsController = [[self storyboard] instantiateViewControllerWithIdentifier:@"LocationsViewSearchResultsNavController"];

    // Our instance of UISearchController will use searchResults
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];


    self.searchController.searchResultsUpdater = self;

    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x,
                                                       self.searchController.searchBar.frame.origin.y,
                                                       self.searchController.searchBar.frame.size.width, 44.0);

    self.tableView.tableHeaderView = self.searchController.searchBar;
    self.definesPresentationContext = true;

    // Load the data on a background queue...
    // As we are using a local file it's not really necessary, but if we were connecting to an online URL then we'd need it
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
        self.RecipeArray = [jsonLoader locationsFromJSONFile:url];
        // Now that we have the data, reload the table data on the main UI thread
        [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
);



// Just before showing the LocationDetailViewController, set the selected Location object
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
    LocationDetailViewController *vc = segue.destinationViewController;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
    vc.location = [self.RecipeArray objectAtIndex:indexPath.row];
    //self.searchController.active = false;



-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

      NSInteger tag = 120;
    cell.contentView.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1.0];
    UIView  *whiteRoundedView = [[UIView alloc]initWithFrame:CGRectMake(6, 5, self.view.frame.size.width-12, cell.contentView.frame.size.height-15)];
    CGFloat colors[]=1.0,1.0,1.0,1.0;//cell color white
    whiteRoundedView.layer.backgroundColor = CGColorCreate(CGColorSpaceCreateDeviceRGB(), colors);
    whiteRoundedView.layer.masksToBounds = false;
    whiteRoundedView.layer.cornerRadius = 3.0;
    whiteRoundedView.layer.shadowOffset = CGSizeMake(-1, 1);
    whiteRoundedView.layer.shadowOpacity = 0.2;
    if (cell.tag !=120) cell.contentView.backgroundColor = [UIColor clearColor];
         [cell.contentView addSubview:whiteRoundedView];
         [cell.contentView sendSubviewToBack:whiteRoundedView];
        cell.tag = tag;



- (void)didReceiveMemoryWarning 
    [super didReceiveMemoryWarning];



#pragma mark - Table View Controller Methods

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LocationCell"];

    Location *location = [self.RecipeArray objectAtIndex:indexPath.row];

//*****recall NSUserDefaults works, but not sure how to compare*******    
    NSMutableArray* array1 = [[NSUserDefaults standardUserDefaults] objectForKey:@"selections"];
    NSLog(@"-----------selections-----------%@", array1);

    cell.textLabel.text = location.name;
    cell.detailTextLabel.text = location.cookTime;
    cell.imageView.image = [UIImage imageNamed:@"recipeicon2.png"];

    return cell;


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath


        return 100;



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
    return [self.RecipeArray count];





@end

第二个表格视图:

@interface FilterViewController () <UISearchResultsUpdating>

@property (nonatomic, strong) NSArray *IngredientsArray;
@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) NSMutableArray *searchResults;
@property (nonatomic, strong) NSMutableSet *selectedRowObjects;
@property (nonatomic, strong) NSMutableDictionary *selectedRows;
@property (nonatomic, strong) NSMutableArray *selections;

@end

@implementation FilterViewController 
    NSArray *_locations;





- (void)viewDidLoad 


    [super viewDidLoad];

    //self.selections = [NSMutableArray array];

    self.selections = [NSMutableArray arrayWithArray:(NSArray *)[[NSUserDefaults standardUserDefaults] objectForKey:@"selections"]];
    if(self.selections == nil)
        self.selections = [[NSMutableArray alloc] init];
    

   //_myMtableArray = [[NSMutableArray alloc] init];

    // Create a new JSONLoader with a local file URL
    JSONLoaderIngreds *jsonLoader = [[JSONLoaderIngreds alloc] init];
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"locations" withExtension:@"json"];

    // There's no transition in our storyboard to our search results tableview or navigation controller
    // so we'll have to grab it using the instantiateViewControllerWithIdentifier: method
    UINavigationController *searchResultsController = [[self storyboard] instantiateViewControllerWithIdentifier:@"FilterViewSearchResultsNavController"];

    // Our instance of UISearchController will use searchResults
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];

    // The searchcontroller's searchResultsUpdater property will contain our tableView.
    self.searchController.searchResultsUpdater = self;

    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x,
                                                       self.searchController.searchBar.frame.origin.y,
                                                       self.searchController.searchBar.frame.size.width, 44.0);

    self.tableView.tableHeaderView = self.searchController.searchBar;
    self.definesPresentationContext = true;


    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
        _locations = [jsonLoader ingredientsFromJSONFile:url];
        // Now that we have the data, reload the table data on the main UI thread
        [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];

        );

    _selectedRows = [[NSMutableDictionary alloc] init];



// Just before showing the LocationViewController, set the selected Location object
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
    LocationsViewController *vc = segue.destinationViewController;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
    vc.location = [_locations objectAtIndex:indexPath.row];



- (void)didReceiveMemoryWarning 
    [super didReceiveMemoryWarning];



#pragma mark - Table View Controller Methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
        //the below code will allow multiple selection
    if ([self.selections containsObject:cell.textLabel.text])
    
        [self.selections removeObject:cell.textLabel.text];
    
    else
    
        [self.selections addObject:cell.textLabel.text];
    
    [tableView reloadData];
    NSLog(@"***************Selected Ingredients**************** %@", _selections);
    NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];

    [userdefaults setObject:_selections forKey:@"selections"];
    [userdefaults synchronize];
    NSLog(@"-------------NSUserDefaults------------%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);





   - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FilterCell"];



    cell.textLabel.text = [_locations objectAtIndex:indexPath.row];
    cell.imageView.image = [UIImage imageNamed:@"ingredientsicon3232.png"];

       if ([self.selections containsObject:cell.textLabel.text])
       
           cell.accessoryType = UITableViewCellAccessoryCheckmark;
       
       else
       
           cell.accessoryType = UITableViewCellAccessoryNone;

       
       return cell;
   


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
    return [_locations count];


@end

【问题讨论】:

【参考方案1】:

JSON 过滤或处理并存储在 NSDictionary 中

然后你需要研究所有的tableview delegate

最终显示在表格视图中

【讨论】:

以上是关于如何比较每个字典中 JSON Array 键值的字符串以查看它们是不是包含 NSUserDefault 字符串并返回 JSON 字典匹配项的主要内容,如果未能解决你的问题,请参考以下文章

字典的操作约束

python 中关于字典的键

如何解析字典中的数组内的字典

php:如何获取键值的索引数组[重复]

javascript中数组取值的问题,如何取出键值对中的值?

如何在 Swift 中将键值对添加到类型为 [String:AnyObject] 的字典中?