Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 814
Gidogeek Avatar asked Dec 27 '22 05:12

Gidogeek


2 Answers

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.

like image 136
Martin R Avatar answered May 03 '23 15:05

Martin R


The first thing is that NSArray cannot contain primitive type of objects like 1, 2, 3. But, does contain object. So, when you create a predicate you should create it in the same way as such that it takes object. The above predicate should be reformed to something like this to work;

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"item_id == %@", @(1)];
like image 44
Sandeep Avatar answered May 03 '23 16:05

Sandeep