Search code examples
iosobjective-cnspredicate

NSPRedicate valueForUndefinedKey


I have a array of ProductData as follows, and I want to filter them based on their category and I applied the following Predicate, but it returns me error.

pTempElements =[[NSMutableArray alloc] initWithArray: [self.pElements filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"category = %@", @"4"]]];

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ valueForUndefinedKey:]: this class is not key value coding-compliant for the key category.'

Here is overlook of the pElements

po self.pElements
<__NSArrayM 0x174241e30>(
<ProductData: 0x17427ce00>,
<ProductData: 0x17427cd80>,
<ProductData: 0x17427ce40>,
<ProductData: 0x17427ce80>,
)

ProductData.m

#import "ProductData.h"

@implementation ProductData
@synthesize pId, pImage, pPrice, pName, pCategory

-(id)initWithDictionary:(NSDictionary *)aDict{
    self = [self init];
    if (self){
        self.pId = [aDict objectForKey:@"id"];
        self.pPrice = [aDict objectForKey:@"price"];
        self.pImage = [aDict objectForKey:@"imagePath"];
        self.pCategory = [aDict objectForKey:@"category"];
        self.pName = [aDict objectForKey:@"name"];
    }
    return self;
}

Solution

  • You should give the property name of the object by which you planning to filter the array. Here I guess it is pCategory. You should rewrite your code as below

    pTempElements =[[NSMutableArray alloc] initWithArray: [self.pElements filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"pCategory == %@", @"4"]]];