Best way to save data in iOS?

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

  • plus or minus money
  • amount of money
  • and a name that has debts (or a name where you have debts)

But I can not save data (NSUserdefaults, Core data, SQLLite)

Maybe you can tell me the best way to save them?

+6
source share
3 answers

The easiest way to store a small amount of data on your device is to use NSUserDefaults. But this way you can save only property lists. The property list is a combination of 6 types of objects: NSNumber, NSString, NSArray, NSDictionary, NSDate, NSData. In your case, this is easy to do. For example, to save a new debt record, you can use the 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 read the list of debts, you read something similar.

But I recommend you use basic data. It is more flexible, and you will not need to write all this code to manage your data (to edit existing records or to delete them). You can significantly expand your model, for example, when you want to keep a debt date. This is a link to a good tutorial.

+10
source

If the number of records is user-defined and will grow using the application, I suggest Core Data, which can be supported by SQLite. If you work in modern Xcode (e.g. Xcode 4), creating models is simple and graphic. If you've ever worked with ORM infrastructure before, an interface for queries, etc. It should be easy to understand.

Find some tutorials, but be specific when looking for tutorials that match your version of Xcode, as master data development has changed a lot lately.

+3
source

Source: https://habr.com/ru/post/918288/


All Articles