从NSUserDefaults中查找数组的索引路径

时间:2014-03-09 05:51:07

标签: ios7 nsmutablearray uicollectionview nsuserdefaults

我有一个UICollectionView,我用它作为过滤器,允许用户直观地选择他们想要浏览的类别。当他们选择(或取消选择)这些类别时,我将这些类别名称放入一个可变数组并将它们存储在NSUserDefaults中。

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

     NSString *selectedCategory = [categoryNames objectAtIndex:indexPath.row];
     [selectedCategories addObject:selectedCategory];

     NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
     [userDefaults setObject:selectedCategories forKey:@"selectedCategory"];
     [userDefaults synchronize]; }


- (void) collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {

     NSString *deSelectedCategory = [categoryNames objectAtIndex: indexPath.row];
     [selectedCategories removeObject:deSelectedCategory];

     NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
     [userDefaults setObject:selectedCategories forKey:@"selectedCategory"];
     [userDefaults synchronize]; }

当用户返回到过滤器屏幕时,我想在他们输入的时候再次预先填充他们在UICollectionView中选择的那些类别。我已经能够使用以下代码撤回存储在NSUserDefaults中的数据:

NSMutableArray *selectedCategories = [[userDefaults objectForKey:@"selectedCategory"]mutableCopy];

我无法弄清楚如何使用我从NSUserDefaults拉回来的数组来比较我的categoryNames数组(它列出所有的类别名称为NSStrings并用于填充cellForItematIndexPath中的UICollectionView)并查找相应的索引路径,以便预先选择正确的UICollectionView单元格。

似乎需要-indexofObject,但我一直在努力正确使用它。

我仍然是ios编程的新手,所以任何代码示例都会非常感激。

1 个答案:

答案 0 :(得分:0)

据推测,您在显示任何单元格之前加载了所选类别名称的列表,例如在viewDidLoad中。在这种情况下,您只需要向cellForRowAtIndexPath添加一些逻辑,以选择类别名称在selectedCategories中的单元格。它可能看起来像这样:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = ...;

    NSString *category = self.categoryNames[indexPath.item];
    if ([self.selectedCategories containsObject:category] && !cell.selected) {
        [self.collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
        // There seems to be a bug in UICollectionView such that the previous
        // statement doesn't trigger the cell's selected view to be displayed.
        // Adding the following statement fixes the issue. Keeping the above
        // statement because it is important when allowsMultipleSelection is NO.
        cell.selected = YES;
    }
}