Filtering NSMutableArray of NSDictionary with NSPr

2019-06-12 01:12发布

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条回答
女痞
2楼-- · 2019-06-12 01:44

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.

查看更多
登录 后发表回答