Delete object from NSMutableArray by key

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

Is it possible to delete an object by key in an object of an array dictionary?

For instance. delete item by age = 27

+4
source share
4 answers

To filter objects from 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- the desired array - this is the first array without the age of 27.

By the way, I know that this is not what you asked for, but such a thing is a great reason to switch to Swift. This is soooooo much easier; this problem is similar to the live neon sign for Swift:

let array = [["name":"Jenny", "age":23],["name":"Daisy", "age":27]]
let array2 = array.filter {$0["age"] != 27}
+8
source

NSPredicate , . NSPredicate , NSArray , - .

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

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age != 27"];
NSArray *filtered = [array filteredArrayUsingPredicate:predicate];

NSLog( @"%@", array );
NSLog( @"%@", filtered );
+4

, , - . , , - , , , . - :

NSInteger indexToDelete = -1;

for (NSInteger i = 0; i < array.count; i++) {
   NSDictionary *dict = array[i];

   if ([dict[@"age"] integerValue] == 27) {
      indexToDelete = i;
      break;      
   }
}

if (indexToDelete > 0) {
   [array removeObjectAtIndex:indexToDelete];
}

, filteredArrayUsingPredicate, Xcode measureBlock. 1000 , , , , , , , , . ( 0,269 0,261 )

, , - , . , filterArrayUsingPredicate . , , measureBlock .:)

+3

, , , .

sqlite , .

+1

Source: https://habr.com/ru/post/1569370/


All Articles