Filtering NSMutableArray of NSDictionary with NSPredicate

梦想与她 提交于 2019-12-08 11:43:02

问题


I'm having an NSObject entity for storing some data like name, id from server

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;
}

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];
}

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?


回答1:


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"];

With

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userName == %@", @"popo"]; and it will work.



来源:https://stackoverflow.com/questions/26480703/filtering-nsmutablearray-of-nsdictionary-with-nspredicate

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