简体   繁体   English

在Objective-C上存储数据

[英]Store Data on Objective-C

I would simply like to create a file that stays around after the program quits. 我只想创建一个程序退出后仍然存在的文件。 I would like it to contain objects that I have initiated, is that possible? 我希望它包含已启动的对象,这可能吗? Or does it just have to have text in it? 还是只在其中包含文字? How can I access that file later? 以后如何访问该文件? Also, is this done the same way on the Mac and the iPhone? 另外,在Mac和iPhone上是否以相同的方式执行此操作?

Take a look at Core Data or SQLite. 看一看Core Data或SQLite。 Apple has some sample code for them, not sure about SQLite because they prefer you tou use core data. Apple为他们提供了一些示例代码,不确定SQLite,因为它们更喜欢您使用核心数据。

I will direct you to this question. 我将引导您解决这个问题。 Adding core data to my iPhone app 将核心数据添加到我的iPhone应用程序

Or use NSUserDefaults: Best way to save data on the iPhone 或使用NSUserDefaults: 在iPhone上保存数据的最佳方法

Yes! 是! It's possible. 这是可能的。

Derive your objects that you want to persist from NSCoding. 从NSCoding派生要保留的对象。 On those objects, implement the initWithCoder and encodeWithCoder functions on those objects. 在这些对象上,对那些对象实现initWithCoder和encodeWithCoder函数。 In these functions, write all of your primitive types to the coder (or read them) using the functions here http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSCoder_Class/Reference/NSCoder.html 在这些函数中,请使用此处的函数将所有原始类型写入编码器(或读取它们),方法是在此处http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSCoder_Class/Reference /NSCoder.html

When you want to save your file, use an NSKeyedArchiver and pass in the object you want to archive along w/ the file name. 当您要保存文件时,请使用NSKeyedArchiver并将要存档的对象与文件名一起传递。

[NSKeyedArchiver archiveRootObject:root toFile:string]; 

More examples here https://stackoverflow.com/questions/2805026/iphone-problem-in-saving-file-using-nscoding 此处有更多示例https://stackoverflow.com/questions/2805026/iphone-problem-in-saving-file-using-nscoding

I have used SQLitePersistentObjects in the past to give my Objective-C class objects an ORM-esque feel and behaviour. 我过去曾使用SQLitePersistentObjects使我的Objective-C类对象具有ORM风格的感觉和行为。 The objects itself translate into corresponding tables in the database, which in this case is a simple SQLite database file. 对象本身转换为数据库中的相应表,在这种情况下,该表是一个简单的SQLite数据库文件。

存档和序列化编程指南也可能很有趣。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM