【问题标题】:Filter Array of Objects with NSPredicate based on NSInteger property in super class基于超类中的 NSInteger 属性使用 NSPredicate 过滤对象数组
【发布时间】:2013-04-08 18:47:40
【问题描述】:

我有以下设置:

@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

#import <Foundation/Foundation.h>
#import "Item.h"

@interface Category : Item {

}

- (NSString *)path;

@end

我有一个包含类别实例(称为“类别”)的数组,我想根据它的 item_id 取出单个项目。这是我使用的代码:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"item_id == %d", 1]; 
NSArray *filteredArray = [categories filteredArrayUsingPredicate:predicate];

这会导致以下错误:

* 由于未捕获的异常“NSUnknownKeyException”而终止应用程序,原因:“[valueForUndefinedKey:]:这个类是 键 item_id 的键值编码不兼容。'

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

【问题讨论】:

  • NSPredicate *predicate = [NSPredicate predicateWithFormat:@"item_id == 1"]; NSArray *filteredArray = [类别filteredArrayUsingPredicate:predicate];
  • @Manohar the 1,不是静态的,它实际上是一个可变的 NSInteger,我将变量的设置留在了示例之外,因为它不应该影响问题或答案。即使我尝试了您的解决方案,但它给出了相同的错误
  • 看看我的回答
  • 您确定要将item_id 属性用作指针吗? NSInteger 不是一个对象,所以也许你只想要NSInteger item_id
  • 感谢@MartinR 修复了它。不知道为什么我将其添加为指针(3年前)。谢谢!请务必添加答案,以便我将其标记为已解决。

标签: objective-c nsarray nspredicate kvc


【解决方案1】:

您已将item_id 属性声明为指针。但是NSInteger 是标量类型(32 位或 64 位整数),所以应该声明为

@property (nonatomic, assign) NSInteger item_id;

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

【讨论】:

  • 如何使用title代替item_id,如果我使用任何属性,我会崩溃?
  • @Sandy:你最好问你自己的问题,你可以提供所有必要的信息。
【解决方案2】:

第一件事是 NSArray 不能包含原始类型的对象,如 1、2、3。但是,确实包含对象。因此,当您创建谓词时,您应该以与它接受对象相同的方式创建它。上面的谓词应该改成这样才能起作用;

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

【讨论】:

  • 我尝试了您的解决方案,但它仍然给了我完全相同的错误。
【解决方案3】:
NSString *str = [NSString stringWithFormat:@"%i",yourIntVariable];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"item_id == %@", str]; 
NSArray *filteredArray = [categories filteredArrayUsingPredicate:predicate];

【讨论】:

  • 这不起作用。问题在其他地方:“这个类不符合键 item_id 的键值编码。”如问题中所述。谓词对我来说也是正确的,因此我很困惑。当过滤不是从基类继承的其他项目时,它可以完美地工作。我相信问题出在 KVC 设置中,而不是 Predicate 中。但这更像是一个有根据的猜测。
猜你喜欢
  • 2017-09-20
  • 1970-01-01
  • 1970-01-01
  • 2021-03-13
  • 2018-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多