如何从NSDictionary获取IndexPath

时间:2016-06-13 15:06:01

标签: ios objective-c nsdictionary nsindexpath

想象一下,我有以下NSDictionary

dict = {
    "a" = [
        obj1,
        obj2,
        obj3
    ],
    "b" = [
        obj4,
        obj5
    ],
    "invalid" = [
        obj6,
        obj7,
        obj8
    ],
    "c" = [
        obj9,
        obj10,
        obj11
    ]
}

此数据用于使用以下TableView中的部分填充NSArray

arr = @[@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z"];

我使用以下方法查找对象

- (void)selectRowWithId:(NSNumber *)uid {
    [dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(id == %@)", uid];
        NSArray *filteredDictArray = [obj filteredArrayUsingPredicate:predicate];
        if ([filteredDictArray count] > 0) {

            NSIndexPath *targetIndexPath = nil;
            //trying to find the NSIndexPath here

            [[self tableView] selectRowAtIndexPath:targetIndexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
            [self tableView:[self tableView] didSelectRowAtIndexPath:targetIndexPath];
        }
    }];
}

假设我将对象设置为obj10

根据我的NSDictionaryNSArrayNSIndexPathSection:2 Row:1

如果我只知道obj10

,如何获得此值?

更新(解决方案)

所以,结合每个人的答案背后的想法和我自己的答案,以下我用过以防万一对某人有帮助。 BTW:这适用于iOS9

- (void)selectRowWithId:(NSNumber *)uid {
    [dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(id == %@)", uid];
        NSArray *filteredDictArray = [obj filteredArrayUsingPredicate:predicate];
        if ([filteredDictArray count] > 0) {

            //trying to find the NSIndexPath here
            NSIndexPath *targetIndexPath = [NSIndexPath indexPathForRow:[[dict objectForKey:key] indexOfObject:filteredPersonsArray[0]] inSection:[arr indexOfObject:key]];

            [[self tableView] selectRowAtIndexPath:targetIndexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle];
            [self tableView:[self tableView] didSelectRowAtIndexPath:targetIndexPath];
        }
    }];
}

1 个答案:

答案 0 :(得分:1)

你的代码有点太棘手了。有时通常的循环更容易。

[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL * stop) 
{
  for( NSInteger index = 0; index < [obj count]; index++ )
  {
    if ([obj[index] isEqualToString:uid])
    {
      // thats the index
      // Let's have a look-up for the section
      NSString *sectionKey = [[key substringToIndex:1] uppercaseString]; //Typo
      for( NSInteger section=0; section < [arr count]; section++ )
      {
        if( [arr[section] isEqualToString:sectionKey] )
        {
          // That's the section
        }
      }
    }
  }
}

输入Safari。