NSPRedicate valueForUndefinedKey

NSPRedicate valueForUndefinedKey

我有一个 ProductData 数组,如下所示,我想根据它们的 category 过滤它们,我应用了以下 Predicate,但它 returns我的错误。

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.'

这里可以俯瞰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;
}

您应该提供您计划用来过滤数组的对象的 属性 名称。这里我猜是pCategory。你应该重写你的代码如下

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