Saturday, June 1, 2013

NSMutableArray removeObjectsInArray example in Objective C (iOS).

NSMutableArray removeObjectsInArray

Removes from the receiving array the objects in another given array.

- (void)removeObjectsInArray:(NSArray *)otherArray

An array containing the objects to be removed from the receiving array.

Discussion of [NSMutableArray removeObjectsInArray]
This method is similar to removeObject:, but allows you to efficiently remove large sets of objects with a single operation. If the receiving array does not contain objects in otherArray, the method has no effect (although it does incur the overhead of searching the contents).

This method assumes that all elements in otherArray respond to hash and isEqual:.

NSMutableArray removeObjectsInArray example.
NSMutableArray *discardedItems = [NSMutableArray array];
SomeObjectClass *item;

for (item in originalArrayOfItems) {
    if ([item shouldBeDiscarded])
        [discardedItems addObject:item];

[originalArrayOfItems removeObjectsInArray:discardedItems];

Example of [NSMutableArray removeObjectsInArray].
works with 2 arrays, ok, but that prevents to make a parsing loop in many situations ;

NSArray* matchingItems = [mainArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@" attributetockeck MATCHES[cd] %@ ", attributevalue]];
[mainArray removeObjectsInArray:matchingItems];

NSMutableArray removeObjectsInArray example.
- (void)deleteSavedItem:(NSString *)keycodeToDelete {
    NSMutableArray * savedItems    = [[self loadAllSavedItems] mutableCopy];
    NSArray        * matchingItems = [savedItems filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@" keycode MATCHES[cd] %@ ", keycodeToDelete]];

    [savedItems removeObjectsInArray:matchingItems];

    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    [defaults setValue:savedItems forKey:@"savedItems"];
    [defaults synchronize];

    [savedItems release];

End of NSMutableArray removeObjectsInArray example article.