【发布时间】: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