An array filter of objects with NSPredicate based on the NSInteger property in the superclass

I have the following setup:

@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 

and

 #import <Foundation/Foundation.h> #import "Item.h" @interface Category : Item { } - (NSString *)path; @end 

I have an array with instances of a category (called "categories") that I would like to take on a single item based on item_id. Here is the code I use for this:

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

This results in the following error:

* Application termination due to the uncaught exception "NSUnknownKeyException", reason: "[valueForUndefinedKey:]: this class is not a key value compatible with the encoding for the item_id key element. '

How can I fix this and what am I doing wrong? the properties are synthesized, and I can access and set the item_id property in the instances of the category.

+4
source share
3 answers

You specified the item_id property as a pointer. But NSInteger is a scalar type (32-bit or 64-bit integer), so you must declare it as

 @property (nonatomic, assign) NSInteger item_id; 

Note. Starting with the LLVM 4.0 compiler (Xcode 4.4), both @synthesize and instance variables are automatically generated.

+4
source

First, NSArray cannot contain a primitive type of object, such as 1, 2, 3. But it contains an object. Therefore, when you create a predicate, you must create it in the same way that it takes an object. The above predicate must be converted to something like this in order to work;

 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"item_id == %@", @(1)]; 
+3
source
 NSString *str = [NSString stringWithFormat:@"%i",yourIntVariable]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"item_id == %@", str]; NSArray *filteredArray = [categories filteredArrayUsingPredicate:predicate]; 
+3
source

All Articles