What are the options for saving data in iOS?

前端 未结 3 1497
旧时难觅i
旧时难觅i 2020-11-30 02:20

I\'d like to serialize a bunch of data and save it to a file, then be able to load it (naturally) and play it back with a feature I have written. (Sorry if my terminology i

相关标签:
3条回答
  • 2020-11-30 02:29

    It depends on the data you are writing. If you mostly want to serialize objects, see the NSCoding protocol. If you have some simple data structure that’s not a class, you can store that into a NSDictionary and save it into a plist. And if you have a big chunk of data (like thousands of floats or something like that), you might want to save that using NSData as you already hinted. In any case be sure to read the Archives and Serializations Programming Guide so that you don’t reinvent the wheel.

    0 讨论(0)
  • 2020-11-30 02:42

    Yes, pretty right direction. You need to implement something, that is called NSCoding protocol on your object to be able to archive & unarchive it into NSData. See the example: Saving files on iOS using NSFileManager

    0 讨论(0)
  • 2020-11-30 02:47

    You can use plist.
    It is very easy to save list of string or other data without using core data.
    See Property List Programming Guide

    For example, this code will save an object (rootObj) which can be an array or a dictionary:

    NSString *error;
    NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *plistPath = [rootPath stringByAppendingPathComponent:@"yourFile.plist"];
    NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:rootObj
                                                                   format:NSPropertyListXMLFormat_v1_0
                                                         errorDescription:&error];
    if(plistData) {
      [plistData writeToFile:plistPath atomically:YES];
    }
    else {
      NSLog(@"Error : %@",error);
      [error release];
    }
    

    There is some limitation on supported class (see the guide)

    0 讨论(0)
提交回复
热议问题