2017-04-10 65 views
0

我有一个ProductData的数组,如下所示,我想根据它们的category对它们进行过滤,并且我应用了以下Predicate,但它会返回错误。NSPRedicate valueForUndefinedKey

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

终止应用程序由于未捕获的异常“NSUnknownKeyException”, 原因:“[valueForUndefinedKey:]:此类 不是关键值编码兼容的关键类别”。

这里是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; 
} 
+2

你可以试试吗? pTempElements = [[NSMutableArray alloc] initWithArray:[self.pElements filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@“pCategory ==%@”,@“4”]]]; –

+0

是的,这工作得很好。 – hotspring

回答

1

俯瞰你应该给由你打算阵列过滤的对象的属性名称。这里我猜这是pCategory。你应该重写你的代码如下

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