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

流过昼夜 提交于 2019-12-10 16:49:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!