Retrieve NSDictionary from NSArray where dictionary key has value X

谁都会走 提交于 2019-11-29 18:12:46

问题


I have an NSArray with NSDictionaries. One of the dictionaries keys in one of the arrays contains a value. I want to retrieve the NSDictionary with that value.

My array:

Array: (
        {
        DisplayName = "level";
        InternalName = "Number 2";
        NumberValue = 1;
    },
        {
        DisplayName = "PurchaseAmount";
        InternalName = "Number 1";
        NumberValue = 3500;
    }
)

So, I would like to get the dictionary which contains DisplayName set to PurchaseAmount (case insensitive).

How can I accomplish that?


回答1:


LIKE[cd] will also do it

NSArray *filtered = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(DisplayName LIKE[cd] %@)", @"purchaseAmount"]];

returned

<NSArray>(
    {
       DisplayName = PurchaseAmount;
       InternaName = "Number 1";
       NumberValue = 3500;
    }
)



回答2:


The following solved my problem:

NSArray *filtered = [promotions filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"(DisplayName == %@)", @"PurchaseAmount"]];
NSDictionary *item = [filtered objectAtIndex:0];

Thnx to user Nate for his comment on my question!




回答3:


Use NSPredicate this way

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"DisplayName LIKE[cd] 'PurchaseAmount' "];
NSArray *filter = [array filteredArrayUsingPredicate:predicate];
NSLog(@"%@",filter);

Here filter will hold your dictionaries which contains DisplayName set to PurchaseAmount (case insensitive)




回答4:


Answer in Swift,

let predicate = NSPredicate(format: "name contains[cd] %@", stringLookingFor)
let newList = data .filteredArrayUsingPredicate(predicate)

The data nsarray looks like this

[
 {
   name = Carlos,
   total = 9
 },
 {
   name = Willy,
   total = 2
 }
]



回答5:


  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"DisplayName == 'level'"];
  NSArray *arrOutput = [[Array filteredArrayUsingPredicate:predicate] mutableCopy];

with the help of above 2 lines you will get all dictionary with DisplayName = "PurchaseAmount"



来源:https://stackoverflow.com/questions/15831183/retrieve-nsdictionary-from-nsarray-where-dictionary-key-has-value-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!