从内存中添加/删除/编辑字典的一种方法

时间:2016-03-15 13:45:25

标签: ios objective-c swift

现在,如果我有NSMutableArry NSDictionaries的列表,我想编辑/删除/添加对象,并保存到用户默认值。 (OBJ-C / SWIFT)

所以我会为每个操作设置一个函数,例如在列表中添加一个函数:

-(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];


}

然后删除另一个方法,另一个方法进行编辑。我很确定这不是一个聪明的解决方案,虽然我不会想到一个简单的解决方案,只需一个明确的方法。

是否有更好的实现,而不是编写3/4方法?

2 个答案:

答案 0 :(得分:0)

每当你向NSUserDefaults保存任何内容时,它都会被保存为Immutable,即每当你从NSUserDefault获取数据时,它都将是Immutable。因此,您首先需要将其向下转换为Mutable对象,然后您可以对该对象执行操作。每个类,无论其NSMutableArray还是NSM​​utableDictionary都有定义添加,删除&更新记录。 要更新您需要的任何现有数据,请在数据源中检查其可用性。然后执行进一步的操作。您甚至可以通过为每个操作定义Enum结构来在单个函数中执行所有任务。

答案 1 :(得分:0)

//
//  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

乐意帮忙:) 玩得开心