Best way to save data to iOS?

后端 未结 3 2071
南方客
南方客 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

    0 讨论(0)
  • 2021-02-09 08:49

    If the quantity of records is user-defined, and will grow with app use, I suggest Core Data, which can be backed by SQLite. If you are working in a modern Xcode (i.e. Xcode 4), creating models is easy and graphical. If you have ever worked with ORM frameworks before, the interface for querying, etc. should be easy to grasp.

    Search around for some tutorials, but be specific about finding tutorials that match your version of Xcode, as Core Data development has been changing a lot lately.

    0 讨论(0)
  • 2021-02-09 08:49

    Good and easy way is to create your own objects and serialize them using NSCodying and NSCopying

    https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSCopying_Protocol/Reference/Reference.html

    https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSCoding_Protocol/Reference/Reference.html

    0 讨论(0)
提交回复
热议问题