Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove object from NSMutableArray by key

NSMutableArray *array = [NSMutableArray arrayWithObjects:@{@"name":@"Jenny",@"age":@23},@{@"name":@"Daisy",@"age":@27},nil];

Is it possible to remove object by key in the array's dictionary object?

For example. remove object by age = 27

like image 806
Jenny Avatar asked Dec 04 '22 04:12

Jenny


1 Answers

To filter objects out of an NSArray, call filteredArrayUsingPredicate:

NSArray *array = @[@{@"name":@"Jenny",@"age":@23},@{@"name":@"Daisy",@"age":@27}];
NSArray *array2 =
  [array filteredArrayUsingPredicate:
   [NSPredicate predicateWithBlock:^BOOL(id obj, NSDictionary *d) {
      return ![[obj valueForKey:@"age"] isEqual:@27];
  }]];

Now array2 is the desired array - it is the first array without the one whose age is 27.

By the way, I know this is not what you asked, but that sort of thing is a great reason to switch to Swift. It is soooooo much simpler; this sort of problem is like a living neon technicolor advertisement for Swift:

let array = [["name":"Jenny", "age":23],["name":"Daisy", "age":27]]
let array2 = array.filter {$0["age"] != 27}
like image 105
matt Avatar answered Dec 20 '22 12:12

matt