【问题标题】:This class is not key value coding-compliant for the key此类与键的键值编码不兼容
【发布时间】:2017-09-27 01:15:52
【问题描述】:

我收到以下错误。 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;
}

【问题讨论】:

  • "kItemId" 似乎是不变的。它的价值是什么?
  • 它只是一个常量字符串id
  • ProductData 没有 id 作为变量。也许你必须用 pId 过滤它
  • 顺便说一句:Objective-C 不是匈牙利语。请尊重命名规则。
  • @AminNegm-Awad 我不明白你的意思。您能否再详细说明一下?

标签: ios objective-c


【解决方案1】:

您的ProductData 没有名为id 的属性,从您的示例代码中我可以看到它有pId

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

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

【讨论】:

    猜你喜欢
    • 2015-08-27
    • 2011-03-17
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    相关资源
    最近更新 更多