简体   繁体   中英

How do I delete particular NSString from NSMutableArray

Help me to sort-out my problem, I've been stuck over here.

I've also seen many questions similar to this, with same problem. But none-of them solved my problem. That's why I need to ask similar question on Stack.

I've NSMutableArray ie NSMutableArray *arrNames = [[NSMutableArray alloc] initWithObjects:@"ABC", @"DEF", @"GHI", nil];

Now I want to delete GHI from this array. So I've tried this way, but it doesn't work-out. Please help me.

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSMutableArray *arrDeletedGTINS = [[NSMutableArray alloc] init];
        arrDeletedGTINS = [userDefaults objectForKey:@"deletedArr"];


NSLog(@"%@", arrDeletedGTINS); will give this output ->

( 00000000000017 )

    if ([arrDeletedGTINS containsObject:@"00000000000017"]) {
        [arrDeletedGTINS removeObject:@"00000000000017"];
    }

    [userDefaults setObject:arrDeletedGTINS forKey:@"deletedArr"];
    [userDefaults synchronize];

If I'm going some-where wrong then please correct me. I'm learning iOS. Please help me.

This line is your issue :

arrDeletedGTINS = [userDefaults objectForKey:@"deletedArr"];

NSUserDefault saves array as NSArray, not as NSMutableArray.
So replace the above line by :

arrDeletedGTINS = [[userDefaults objectForKey:@"deletedArr"] mutableCopy];

Try this.

You can use containsObject method in an NSMutableArray

if ([arrNames containsObject:@"GHI"]) {
    [arrNames removeObject:@"GHI"];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM