将数据保存到 iOS 的最佳方法? [英] Best way to save data to iOS?

查看:34
本文介绍了将数据保存到 iOS 的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序 (iOS 5) 中,我想保存数据 - 我想节省债务.所以它:

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

  • 加或减钱
  • 金额
  • 以及欠债的姓名(或欠债的姓名)

但我不知道如何保存数据(NSUserdefaults、Core data、SQLLite)

But I don't how to save the data (NSUserdefaults,Core data, SQLLite)

也许你能告诉我保存它们的最佳方法?

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

推荐答案

在设备上存储少量数据的最简单方法是使用 NSUserDefaults.但只能以这种方式保存属性列表.属性列表是 6 种类型的对象的组合,NSNumber、NSString、NSArray、NSDictionary、NSDate、NSData.在您的情况下,这很容易做到.例如,要保存新的债务记录,您可以使用以下方法:

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

这篇关于将数据保存到 iOS 的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆