此类不是密钥的密钥值编码兼容

时间:2017-04-28 20:23:03

标签: ios objective-c

我收到以下错误。 restaurantData.itemArray包含ProductData个对象的数组,我正在尝试使用id对其进行过滤,如下所示。我想知道我在实施中做错了什么。

  

***由于未捕获的异常终止应用' NSUnknownKeyException',原因:' [valueForUndefinedKey:]:此类   密钥ID不符合密钥值编码。'

+ (NSString *)menuItemForItemId:(NSString *)itemId
{
    ProductData *restaurantData = [ProductData restaurantDataInstance];

    NSString *item = @"";

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%K == %@)", kItemId, itemId];
    // the error is thrown in the following line
    NSArray *filteredArray = [restaurantData.itemArray filteredArrayUsingPredicate:predicate];
    if ([filteredArray count] > 0)
        item = [(NSDictionary *)[filteredArray objectAtIndex:0] objectForKey:kItem];

    return item;
}

如果需要,这是我的ProductData课程。

ProductData.m

#import "ProductData.h"

#define kTitleKey        @"pName"
#define kPriceKey        @"price"
#define kIdKey           @"id"

@implementation ProductData
@synthesize pId, pImage, pPrice, pName, itemArray;

+(ProductData*) restaurantDataInstance {
    static ProductData *restaurantDataInstance;
    @synchronized(self) {
        if(!restaurantDataInstance){
            restaurantDataInstance = [[ProductData alloc] init];
        }
    }
    return restaurantDataInstance;
}

- (id)init
{
    if (self = [super init]) {
        if (!itemArray || !itemArray.count){
            itemArray = [NSMutableArray arrayWithCapacity:10];
        }
    }
    return self;
}

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

1 个答案:

答案 0 :(得分:2)

您的ProductData没有名为id的媒体资源,您可以从示例代码中看到它有pId

以下行尝试访问名为id的属性,该属性不存在。

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%K == %@)", kItemId, itemId];