Filter Array of Objects with NSPredicate based on NSInteger property in super class

Gidogeek picture Gidogeek · Apr 16, 2013 · Viewed 9.3k times · Source

I've got 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've got an array with Category instances (called 'categories') that I'd like to take a single item out based on it's item_id. Here is the code I use for that:

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

This leads to the following error:

* Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ valueForUndefinedKey:]: this class is not key value coding-compliant for the key item_id.'

How can I fix this and what am I doing wrong? the properties are synthesized and I can acces and set the item_id property successfully on Category instances.

Answer

Martin R picture Martin R · Apr 16, 2013

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

@property (nonatomic, assign) NSInteger item_id;

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