使用 NSPredicate 过滤 NSDictionary 的 NSMutableArray [英] Filtering NSMutableArray of NSDictionary with NSPredicate
问题描述
我有一个 NSObject 实体来存储一些数据,比如来自服务器的名称、id
I'm having an NSObject entity for storing some data like name, id from server
NSObject 文件如下所示,
NSObject file looks like below,
@interface MyEntity : NSObject
@property(nonatomic,strong)NSString *userId;
@property(nonatomic,strong)NSString *userName;
- (id)initWithJSON:(NSDictionary *)dataDict;
@end
- (id)initWithJSON:(NSDictionary *)dataDict
{
if (self = [super init])
{
self.userId = [dataDict objectForKeyNotNull:@"userId"] ;
self.userName = [dataDict objectForKeyNotNull:@"userName"] ;
}
return self;
}
我将值从服务器存储到 NSMutableArray,
I'm storing the values from server to an NSMutableArray by,
NSMutableArray *array = [[NSMutableArray alloc] initWithArray:responseData[@"result"]];
for (NSDictionary *dict in array) {
MyEntity *ent = [[MyEntity alloc] initWithJSON:dict];
[myArray addObject:ent];
}
现在,我想使用 NSPredicate 通过一些用户名过滤 NSMutableArray.我试过下面的代码,
Now, I want to filter that NSMutableArray by some usernames using NSPredicate. I've tried below code,
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY MyEntity.userName == %@", @"popo"];
NSArray *predicateFilteredArray = [myArray filteredArrayUsingPredicate:predicate];
[myArray removeAllObjects];
[myArray addObjectsFromArray:predicateFilteredArray];
它不起作用.我怎样才能做到这一点?
it's not working. How can I achieve this?
推荐答案
你只是不需要用它的实体名称检查谓词写一个简单的谓词,它会起作用我的意思是替换你的代码
You just do not need to check predicate with its entity name write simple predicate and it will work I mean replace your code
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY MyEntity.userName == %@", @"popo"];
与
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userName == %@", @"popo"];
它会起作用.
这篇关于使用 NSPredicate 过滤 NSDictionary 的 NSMutableArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!