如何在NSArray中找到具有匹配键值的字典索引 - Swift

时间:2016-02-24 10:43:09

标签: ios swift nsarray nsdictionary

(
        {
        "date" = "23-02-2016";
        filename = "65.pdf";
    },
        {
        "date" = "23-02-2016";
        filename = "78.pdf";
    },
        {
        "date" = "23-02-2016";
        filename = "abc.pdf";
    }
)

我有一个像这样的数组。我想找到filename =“abc.pdf”的词典的索引。我怎么找到?我的数组是NSArray,字典是NSMutableDictionary。 如果有人能指导我,那将是很有帮助的。

谢谢..

4 个答案:

答案 0 :(得分:0)

var fileterArray: NSArray = yourArray.filteredArrayUsingPredicate(NSPredicate(format: "self.%@ contains[c] %@", "filename", "abc.pdf"))

for (NSInteger i=0;i<fileterArray.count:i++){
     NSInteger anIndex=[yourArray indexOfObject:[fileterArray objectAtIndex:i]];
     NSLog(@"%d",anIndex);
}

答案 1 :(得分:0)

我创建了样本NSMutableDictionary和NSArray。使用谓词收集filterArray中的“abc.pdf”文件名并将其循环以获取索引。

    let dic1 : NSMutableDictionary = NSMutableDictionary.init(object: "23-02-2011", forKey: "date");
    dic1.setValue("65.pdf", forKey: "filename");
    let dic2 : NSMutableDictionary = NSMutableDictionary.init(object: "23-02-2012", forKey: "date");
    dic2.setValue("65.pdf", forKey: "filename");
    let dic3 : NSMutableDictionary = NSMutableDictionary.init(object: "23-02-2013", forKey: "date");
    dic3.setValue("abc.pdf", forKey: "filename");
    let dic4 : NSMutableDictionary = NSMutableDictionary.init(object: "23-02-2014", forKey: "date");
    dic4.setValue("abc1.pdf", forKey: "filename");
    let dic5 : NSMutableDictionary = NSMutableDictionary.init(object: "23-02-2015", forKey: "date");
    dic5.setValue("abc.pdf", forKey: "filename");


    let testArray :NSArray = NSArray.init(array: [dic1,dic2,dic3,dic4,dic5]);
    let filterArray: NSArray = testArray.filteredArrayUsingPredicate(NSPredicate(format: "self.%@ contains[c] %@", "filename", "abc.pdf"));

    for(var i = 0; i < filterArray.count; i++) {
        let anIndex: NSInteger = testArray.indexOfObject(filterArray[i]);
        NSLog("%d",anIndex);
    }

如果字典值重复,它将为您提供过滤器数组值,您将在此处获取所有值索引。

答案 2 :(得分:0)

请尝试使用此代码段。

  let fileArray = yourArray.valueForKey("filename")        
  let indexofDict = fileArray.indexOfObject("abc.pdf")
  print(indexofDict)

答案 3 :(得分:0)

尝试一次。

  NSIndexSet *indexes = [array indexesOfObjectsPassingTest:^BOOL(id obj,NSUInteger idx, BOOL *stop){
  NSString *s = (NSString*)obj;
  NSRange range = [s rangeOfString: searchString];
 return range.location != NSNotFound;
}];