NSPredicate does not work for filtering in ios
I have tried filtering NSPredicate. It doesn't work on NSMutableArray, but I tried on an array and it works fine.
Working code using array:
filterArray=[NSMutableArray arrayWithObjects:@"Yvan",@"Balu",@"Srinath",@"Aswin",@"Ram", nil];
NSPredicate *bPredicate =[NSPredicate predicateWithFormat:@"SELF beginswith[c] 'r'"];
NSArray *resultAr = [resultArray filteredArrayUsingPredicate:bPredicate];
NSLog(@"Output %@",resultAr);
correctly produces:
Output (
Srinath,
Ram
)
I've tried using NSMutableArray with dictionary data, but it doesn't work.
Framing the result array:
for(int i=0;i<[priceArray count];i++)
{
cellDict=[[NSMutableDictionary alloc]init];
NSString *nameStr=nameArray[i];
[cellDict setObject:nameStr forKey:@"Name"];
[cellDict setObject:@([splPriceArray[i] intValue]) forKey:@"Percentage"];
[cellDict setObject:@([priceArray[i] intValue]) forKey:@"Price"];
[resultArray addObject:cellDict];
}
Array of results:
(
{
Name = "Black Eyed Peas";
Percentage = 0;
Price = 80;
},
{
Name = "Black Gram";
Percentage = 0;
Price = 56;
},
{
Name = "Channa White";
Percentage = 0;
Price = 100;
},
{
Name = "Double Beans";
Percentage = 0;
Price = 95;
},
{
Name = "Gram Dall";
Percentage = 0;
Price = 100;
},
{
Name = "Green Moong Dal";
Percentage = 0;
Price = 150;
},
{
Name = "Ground Nut";
Percentage = 0;
Price = 140;
},
{
Name = "Moong Dal";
Percentage = 0;
Price = 75;
},
{
Name = "Orid Dal";
Percentage = 0;
Price = 100;
},
{
Name = "Toor Dal";
Percentage = 0;
Price = 150;
}
)
Trial predicates:
// NSPredicate *predit=[NSPredicate predicateWithFormat:@"Price contains[c] '100'"];
NSPredicate *pred=[NSPredicate predicateWithFormat:@"(Price == %@) AND (Percentage == %@)", @"100",@"0"];
NSArray *resultAr = [resultArray filteredArrayUsingPredicate:predit];
Is this correct above or is there a better way to implement it to get:
expected output:
(
{
Name = "Channa White";
Percentage = 0;
Price = 100;
},
{
Name = "Gram Dall";
Percentage = 0;
Price = 100;
},
{
Name = "Orid Dal";
Percentage = 0;
Price = 100;
}
)
+3
source to share
1 answer
- Should be
Price
notPrice
, should bePercentage
notPercentage
- I think
Percentage
- typeNSNumber
I am testing
NSDictionary * dic1 = @{
@"Name" : @"Black Eyed Peas",
@"Percentage":@(0),
@"Price" : @(80),
};
NSDictionary * dic2 = @{
@"Name" : @"Black Eyed Peas",
@"Percentage":@(0),
@"Price" : @(100),
};
NSMutableArray * mutableArray = [[NSMutableArray alloc] initWithArray:@[dic1,dic2]];
NSPredicate *pred= [NSPredicate predicateWithFormat:@"(Price == %@) AND (Percentage == %@)", @(100),@(0)];
NSArray *resultAr = [mutableArray filteredArrayUsingPredicate:pred];
NSLog(@"%@",resultAr);
Magazine
2015-07-20 22:11:44.535 OCTest[2192:79846] (
{
Name = "Black Eyed Peas";
Percentage = 0;
Price = 100;
}
)
+1
source to share