One method to add/remove/edit dictionaries from memory

Right now, if i have a list , NSMutableArry of NSDictionaries, and i would like to edit / remove/ add object to, and save to the user defaults . (obj-c/swift)

So i would have a function for each operation , for example to add one to the list :

-(void)addMedicineToArray:(NSDictionary*)medicine
{
    NSMutableArray *medicines=[[NSMutableArray alloc] init];
    medicines=[[[NSUserDefaults standardUserDefaults] objectForKey:@"Medicines"] mutableCopy];
    if(!medicines)
        medicines=[[NSMutableArray alloc] init];

    [medicines addObject:medicine];

    [[NSUserDefaults standardUserDefaults] setObject:medicines forKey:@"Medicines"];
    [[NSUserDefaults standardUserDefaults] synchronize];


}

Then another method to remove, and another one to edit. I am pretty sure this is not that clever solution, although i coudn't think of a simple solution to do that in one clear method.

is there some better implementation of this instead of writing 3/4 methods ?

Answers


//
//  MYCustomViewControllerClass.m
//  Fro StackOverFlow
//
//  Created by Naresh Reddy M on 16/03/16.
//  Copyright © 2016 Naresh Reddy M. All rights reserved.
//

#import "MYCustomViewControllerClass.h"
typedef NS_ENUM(NSInteger, EditingType)
{
    kEditingTypeDeleteObj = 1,
    kEditingTypeUpdateObj = 2,
    kEditingTypeAddObj = 3,
    // if needed,Add few More as per your requirement .
};
@implementation MYCustomViewControllerClass
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Forming Medicine Data Dict & Array
    NSMutableArray <NSDictionary *>*medicinesArray;
    if([[[NSUserDefaults standardUserDefaults] objectForKey:@"MYMeds"]  mutableCopy])
        medicinesArray = [[[NSUserDefaults standardUserDefaults] objectForKey:@"MYMeds"]  mutableCopy];
    else
    {
        medicinesArray = [NSMutableArray new];
        for(int i = 0; i < 10 ; ++i)
        {
            NSMutableDictionary *medicineDetailsDict = [NSMutableDictionary new];
            [medicineDetailsDict setValue:[NSString stringWithFormat:@"Medicine : %d",1+i] forKey:[NSString stringWithFormat:@"Name"]];
            [medicineDetailsDict setValue:[NSString stringWithFormat:@"D%d",1+i] forKey:[NSString stringWithFormat:@"DrugID"]]; // Please do maintain a UNIQUE ID for Your Drug
            // You can have other info about drug with appropriate keys

            [medicinesArray addObject:medicineDetailsDict];
        }
    }

    // 1 - Deleting your medicine with DrugID  D1  from aray & saving updated medicines Array into userdefaults
    // Name will be changed for Medicine With DrugID - D1 from @"Medicine : 1" to @"Updated Data for Name Key"
    NSMutableDictionary *medicine1 = [medicinesArray[0] mutableCopy];
    [medicine1 setValue:@"Updated Data for Name Key" forKey:@"Name"]; // Im updating its name here
    [self updateMedicine:medicine1 inToArray:medicinesArray withUpdateType:kEditingTypeUpdateObj];
    // Name of Medicine With D1 Id Has been Updated


    // 2 - Adding New Medicince To your Array & saving updated Array In user defaults
    NSMutableDictionary *myNewMed = [NSMutableDictionary new];
    [myNewMed setValue:@"D150" forKey:@"DrugID"];
    [myNewMed setValue:@"New Named Drug" forKey:[NSString stringWithFormat:@"Name"]];
    NSLog(@"%@",[medicinesArray description]); // D150 will be Added
    [self updateMedicine:myNewMed inToArray:medicinesArray withUpdateType:kEditingTypeAddObj];
    NSLog(@"%@",[medicinesArray description]); // D150 Has been Added


    // 3 - Deleting A Medicine From DB
    // D150 Will be Deleted
    [self updateMedicine:myNewMed inToArray:medicinesArray withUpdateType:kEditingTypeDeleteObj];
    medicinesArray = [[[NSUserDefaults standardUserDefaults] objectForKey:@"MYMeds"]  mutableCopy];
    NSLog(@"%@",[medicinesArray description]); // D150 Was deleted
}
-(void)updateMedicine:(NSMutableDictionary *)updatedMedicine inToArray:(NSMutableArray <NSDictionary *>*)arrayOfMedicines withUpdateType:(EditingType)editType
{
    switch (editType)
    {
        case kEditingTypeDeleteObj:
        {
            NSString *idOfRecivedDrug = updatedMedicine[@"DrugID"];
            for(NSDictionary *med in arrayOfMedicines)
            {
                if([med[@"DrugID"] isEqualToString:idOfRecivedDrug])
                {
                    NSInteger index = [arrayOfMedicines indexOfObject:med];
                    [arrayOfMedicines removeObjectAtIndex:index];
                    [[NSUserDefaults standardUserDefaults] setObject:arrayOfMedicines forKey:@"MYMeds"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
            }
        }
            break;
        case kEditingTypeAddObj:
        {
            NSString *idOfRecivedDrug = updatedMedicine[@"DrugID"];
            bool bIsDrugFound = false;
            for(NSDictionary *med in arrayOfMedicines)
            {
                if([med[@"DrugID"] isEqualToString:idOfRecivedDrug])
                {
                    bIsDrugFound = true;
                    break;
                }
            }
            if(bIsDrugFound)
                NSLog(@"Seems you are trying to add drug to existing UNIQUE ID,Try Updating Other than adding it as a new");
            else
            {
                [arrayOfMedicines addObject:updatedMedicine];
                [[NSUserDefaults standardUserDefaults] setObject:arrayOfMedicines forKey:@"MYMeds"];
                [[NSUserDefaults standardUserDefaults] synchronize];            }
        }
            break;
        case kEditingTypeUpdateObj:
        {
            NSString *idOfRecivedDrug = updatedMedicine[@"DrugID"];
            for(NSDictionary *med in arrayOfMedicines)
            {
                if([med[@"DrugID"] isEqualToString:idOfRecivedDrug])
                {
                    // Found Your Drug now Need to edit it's data
                    NSInteger index = [arrayOfMedicines indexOfObject:med];
                    [arrayOfMedicines replaceObjectAtIndex:index withObject:updatedMedicine];
                    [[NSUserDefaults standardUserDefaults] setObject:arrayOfMedicines forKey:@"MYMeds"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    break;
                }
                else
                    NSLog(@"Your medicine was new,probably need to add it into the dictionary");

            }
        }
            break;
        default:
            break;
    }
}
@end

Happy To Help :) Have Fun


whenever you save anything to NSUserDefaults then it get saved as Immutable i.e. whenever you fetch data from NSUserDefault it will be Immutable. So you need first to downcast it to Mutable object and then you can perform operations on that object. Each class whether its NSMutableArray or NSMutableDictionary have methods defined to add, remove & update the records. To update any existing data you need first to check its availability in the data source & then perform further operation required. You can even perform all tasks in a single function by having a Enum structure define for each operation.


Need Your Help