Objective c 基于超类中NSInteger属性的NSPredicate对象筛选数组

Objective c 基于超类中NSInteger属性的NSPredicate对象筛选数组,objective-c,nsarray,nspredicate,kvc,Objective C,Nsarray,Nspredicate,Kvc,我有以下设置: @interface Item : NSObject { NSInteger *item_id; NSString *title; UIImage *item_icon; } @property (nonatomic, copy) NSString *title; @property (nonatomic, assign) NSInteger *item_id; @property (nonatomic, strong) UIImage *item_ic

我有以下设置:

@interface Item : NSObject {
    NSInteger *item_id;
    NSString *title;
    UIImage *item_icon;
}

@property (nonatomic, copy) NSString *title;
@property (nonatomic, assign) NSInteger *item_id;
@property (nonatomic, strong) UIImage *item_icon;

- (NSString *)path;

- (id)initWithDictionary:(NSDictionary *)dictionairy;

@end

这会导致以下错误:

*由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[valueForUndefinedKey:]:此类为 不符合关键项_id'的键值编码


我如何解决这个问题?我做错了什么?属性已合成,我可以在类别实例上成功访问和设置item_id属性。

首先,NSArray不能包含原始类型的对象,如1、2、3。但是,确实包含对象。所以,当你创建一个谓词时,你应该以它接受对象的相同方式来创建它。上面的谓词应该改成这样才能工作

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"item_id == %@", @(1)];

您已将
item\u id
属性声明为指针。但是
NSInteger
是一种标量类型(32位或64位整数),因此您应该将其声明为

@property (nonatomic, assign) NSInteger item_id;

备注:从LLVM 4.0编译器(Xcode 4.4)开始,
@synthesis
和实例变量都会自动生成。

NSPredicate*谓词=[NSPredicate predicateWithFormat:@“item_id==1”];NSArray*filteredArray=[类别filteredArray使用谓词:谓词]@Manohar 1不是静态的,它实际上是一个NSInteger,它是可变的,我把变量的设置放在示例之外,因为它不应该影响问题或答案。尽管我尝试了您的解决方案,但它也会产生相同的错误请查看我的答案您确定要将
item\u id
属性作为指针吗
NSInteger
不是一个对象,所以您可能只需要
NSInteger item\u id
。谢谢@MartinR修复了它。不知道为什么我把它作为一个指针(3年前)。谢谢请确保您添加了一个答案,以便我可以将其标记为已解决。我尝试了您的解决方案,但仍然会出现完全相同的错误。这不起作用。问题在别处:“此类不符合关键项_id的键值编码。”如问题中所述。谓词在我看来也是正确的,因此我感到困惑。当对其他项进行筛选时(这些项不是从基类继承的),它可以完美地工作。我认为问题在于KVC设置,而不是谓词。但这更像是一个有根据的猜测。如果我在使用任何财产,我会崩溃,如何使用标题就地项_id?@Sandy:你最好问自己的问题,你可以提供所有必要的信息。
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"item_id == %@", @(1)];
NSString *str = [NSString stringWithFormat:@"%i",yourIntVariable];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"item_id == %@", str]; 
NSArray *filteredArray = [categories filteredArrayUsingPredicate:predicate];
@property (nonatomic, assign) NSInteger item_id;