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?
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;
}
)
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!
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)
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
}
]
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