Best way to save data to iOS?

后端 未结 3 2074
南方客
南方客 2021-02-09 08:07

In my application (iOS 5) I want to save data - I want to save debts. So its:

  • plus or minus money
  • the amount of money
  • and the name who has the de
3条回答
  •  粉色の甜心
    2021-02-09 08:26

    The easiest way to store small amount of data on your device is to use NSUserDefaults. But only property lists could be saved in this way. A property list is a combination of objects of 6 types, NSNumber, NSString, NSArray, NSDictionary, NSDate, NSData. In your case it's easy to do. For example, to save a new debt record you can use following method:

    #define DEBTS_LIST_KEY @"listOfAllDebts"
    #define DEBTOR_NAME_KEY @"debtorName"
    #define DEBT_AMOUNT_KEY @"amountOfDebt"
    
    -(void) saveDebt:(CGFloat) debtAmount forName:(NSString *) debtorName
    {
        // pointer to standart user defaults
        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
        // the mutalbe array of all debts
        NSMutableArray * alldebtRecords = [[defaults objectForKey:DEBTS_LIST_KEY] mutableCopy];
        // create new record
        // to save CGFloat you need to wrap it into NSNumber
        NSNumber * amount = [NSNumber numberWithFloat:debtAmount];
    
        NSDictionary * newRecord = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:amount,debtorName, nil] forKeys:[NSArray arrayWithObjects:DEBT_AMOUNT_KEY, DEBTOR_NAME_KEY, nil]];
        [alldebtRecords addObject:newRecord];
        [defaults setObject:alldebtRecords forKey:DEBTS_LIST_KEY];
        // do not forget to save changes
        [defaults synchronize];
    }
    

    To readList of debts you have read something similar.

    But I recommend you to use core data. It's more flexible and you won't have to write all this code to manage your data (to edit existed records, or to delete them). You will be able to extend your model much easier, for example, when you want to save the date of the debt. This is the link to a good tutorial

提交回复
热议问题