Is it possible to store an NSMutableArray together with all its contents into a file and restore it later from there?

偶尔善良 提交于 2019-12-11 05:35:20

问题


Some kind of serialization available in iPhone OS? Is that practically possible or should I quickly forget about that?

I am making a tiny app that stores some inputs in an NSMutableArray. When the user leaves, the inputs should stay alive until he/she returns to continue adding or removing stuff to/from that array.

When the app quits, there must be some way to store all the stuff in the array in a file. Or must I iterate over it, rip everything out and write it i.e. comma-separated somewhere, then the next time go in again, read the stuff in, and iterate over the lines in the file to make an array with that data? That would be hard like a brick. How to?


回答1:


The easy way, since you already have an NSArray object is to write the array to disk using

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag

and read it back in with:

- (id)initWithContentsOfFile:(NSString *)aPath

or

+ (id)arrayWithContentsOfFile:(NSString *)aPath

You can also use NSCoder.

You can probably search sof for the right code.




回答2:


So long as the objects in the array implement NSCoding (NSString and NSValue do; if you're storing your own objects it's relatively straightforward), you can use:

[NSKeyedArchiver archiveRootObject: array toFile: filePath];

to save and:

array = [NSKeyedUnarchiver unarchiveObjectWithFile: filePath];

to load.

You can similarly load/save to NSData.




回答3:


The iPhone SDK is designed to store data using SQLite tables.




回答4:


You can use NSPropertyListSeralization, since NSArray is a type of property list. You can find more information here.



来源:https://stackoverflow.com/questions/1273725/is-it-possible-to-store-an-nsmutablearray-together-with-all-its-contents-into-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!