问题
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.
回答1:
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.
回答2:
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)];
回答3:
NSString *str = [NSString stringWithFormat:@"%i",yourIntVariable];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"item_id == %@", str];
NSArray *filteredArray = [categories filteredArrayUsingPredicate:predicate];
来源:https://stackoverflow.com/questions/16035775/filter-array-of-objects-with-nspredicate-based-on-nsinteger-property-in-super-cl