Mahmoud
Mahmoud

Reputation: 757

how to remove an NSMutableArray object by key?

i have structured an NSMutableArray and here is an example

( { Account = A; Type = Electricity; }, { Account = B; Type = Water; }, { Account = C; Type = Mobile; } )

when i try to delete Account B using

[data removeObject:@"B"];

Nothing Happens

[[NSUserDefaults standardUserDefaults] synchronize];
NSArray *archivedArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[self dataFilePath]];
if (archivedArray == nil) {
    data = [[NSMutableArray alloc] init];           
} else {
    data = [[NSMutableArray alloc] initWithArray:archivedArray];
}

Upvotes: 1

Views: 5675

Answers (3)

Dair
Dair

Reputation: 16240

Alternative: try a NSMutableDictionary:

NSArray *accounts = [NSArray arrayWithObjects:@"A", @"B", @"C", nil];
NSArray *types = [NSArray arrayWithObjects:@"Electricity", @"Water", @"Mobile", nil];

NSMutableDictionary* data = [NSMutableDictionary dictionaryWithObjects:types forKeys:accounts];
[data removeObjectForKey:@"B"];

Upvotes: 0

Antwan van Houdt
Antwan van Houdt

Reputation: 6991

An NSArray is like a list of pointers, each pointer points to an object.

If you call:

[someArray removeObject:@"B"];

You create a new NSString object that contains the string "B". The address to this object is different from the NSString object in the array. Therefore NSArray cannot find it.

You will need to loop through the array and determine where the object is located, then you simply remove it by using removeObjectAtIndex:

Upvotes: -1

jtbandes
jtbandes

Reputation: 118681

If you're actually using an array and not a dictionary, you need to search for the item before you can remove it:

NSUInteger index = [data indexOfObjectPassingTest:^BOOL (id obj, NSUInteger idx, BOOL *stop) {
    return [[(NSDictionary *)obj objectForKey:@"Account"] isEqualToString:@"B"];
}];

if (index != NSNotFound) {
    [data removeObjectAtIndex:index];
}

Upvotes: 8

Related Questions