简体   繁体   中英

Filtering NSMutableArray of NSDictionary with NSPredicate

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM