2017-04-10 71 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"]]];