Best way to save data to iOS?(将数据保存到 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 的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将数据保存到 iOS 的最佳方法?
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01