【问题标题】:Finding index of NSMutableDictionary inside an NSMutableArray在 NSMutableArray 中查找 NSMutableDictionary 的索引
【发布时间】:2016-10-12 15:50:49
【问题描述】:

我有一个带有特定 keyvalue 的 NSMutableDictionary。该字典位于 NSMutableArray 中。我想用数组内某个索引处的特定键更新字典。我想找到这个字典对象的索引。目前,我的字典在索引 0 处,而我的 editingIndexPath 是 1,属于 NSIndexPath 类型,所以 editingIndexPath.row 对我没有帮助。

我的代码如下:

    //UpdatedDateAndTime is the NSMutableArray.
    //selectedDay is a NSString object.
    //dateKeySelected is also a string key.

    [[updatedDateAndTime objectAtIndex:editingIndexPath.row] setObject:selectedDay forKey:dateKeySelected];

我的问题是我想获得找到的字典的正确索引。

【问题讨论】:

  • 上述代码有什么问题?它设置了密钥吗?字典的索引不是和editingIndexPath.row一样吗?
  • @TejaNandamuri...不!如果字典已经存在于数组中怎么办。对我来说,它位于index,值为0,而在表格视图中,我对应于该字典的单元格是editingIndexPath.row,即1。我想要字典对应的数组索引。
  • 你怎么知道这是索引 1 的那个?您如何比较字典?
  • @Larme..我的评论可能会给你答案。
  • @Ron NSMutableArray 是否包含不同的类或所有 NSMutableDictionary?

标签: ios objective-c nsmutablearray nsmutabledictionary


【解决方案1】:

答案曾经是一个带有计数器的 for 循环,但你很幸运:NSArray 有一个新方法 indexOfObject:,它应该可以很好地解决问题:

NSUInteger i = [myArray indexOfObject:@{myKey:myValue}];

斯威夫特:index(of:)

【讨论】:

  • 我得到了这么长的索引值。 '9223372036854775807`
  • 谢谢!我能够得到正确的索引。为什么我得到这个索引是因为我没有传递正确的字典对象。
【解决方案2】:

如果您的数组只包含一个特殊的NSMutableDictionary,请使用以下代码。我没有测试它,但想法是在数组中搜索NSMutableDictionary 类。您必须在indexPath 中进行此搜索,这等于您要分配一些数据的单元格。

@interface ViewController (){
    NSMutableArray *array;
    NSMutableDictionary *dictionary;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

}

- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (indexPath.row == 1) {
        for (int i = 0; i < array.count; i++) {
            if ([updatedDateAndTime[i] objectForKey:@"open_house_updated_date"] == selectedDay) {
            NSLog(@"%i th index contains NSMutableDictionary that you want",i);
            //do whatever needed
            break;
        }
        }
    }
    else{
        //define other cells which doesn't contain NSMutableDictionary
    }
    return cell;
}

@end

我希望这就是你要找的。​​p>

【讨论】:

  • 非常感谢您的支持。但是,该数组由许多 NSMutableDictionary 对象组成。因此,情况并非如此。
  • 所以必须有一个标准来检查正确的字典,那是什么?
  • NSString *dateKeySelected = @"open_house_updated_date"; ` NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K != NULL", dateKeySelected]; // 有键的字典` NSArray *filteredArray = [updatedDateAndTime filteredArrayUsingPredicate:predicateString]; NSMutableDictionary *updatedDay = [[NSMutableDictionary alloc] init]; [updatedDay setObject:selectedDay forKey:@"open_house_updated_date"];
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-24
  • 2011-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-13
相关资源
最近更新 更多