Saving a NSArray

前端 未结 3 1954
忘掉有多难
忘掉有多难 2020-12-02 17:23

I would like to save an NSArray either as a file or possibly use user defaults. Here\'s what I am hoping to do.

  1. Retrieve already saved NSArray (if any).
  2. <
相关标签:
3条回答
  • 2020-12-02 18:12

    NSArray provides you with two methods to do exactly what you want: initWithContentsOfFile: and writeToFile:atomically:

    A short example might look like this:

    //Creating a file path under iOS:
    //1) Search for the app's documents directory (copy+paste from Documentation)
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    //2) Create the full file path by appending the desired file name
    NSString *yourArrayFileName = [documentsDirectory stringByAppendingPathComponent:@"example.dat"];
    
    //Load the array
    NSMutableArray *yourArray = [[NSMutableArray alloc] initWithContentsOfFile: yourArrayFileName];
    if(yourArray == nil)
    {
        //Array file didn't exist... create a new one
        yourArray = [[NSMutableArray alloc] initWithCapacity:10];
    
        //Fill with default values
    }
    ...
    //Use the content
    ...
    //Save the array
    [yourArray writeToFile:yourArrayFileName atomically:YES];
    
    0 讨论(0)
  • 2020-12-02 18:19

    You could implement NSCoding on the objects the array contains and use NSKeyedArchiver to serialize/deserialize your array to disk.

    BOOL result = [NSKeyedArchiver archiveRootObject:myArray toFile:path];
    

    The archiver will defer to your NSCoding implementation to get serializable values from each object and write a file that can be read with NSKeyedUnarchiver:

    id myArray = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    

    More info in the serialization guide.

    0 讨论(0)
  • This would seem to be a problem most suited to Core Data as this will deal with all the persistent object data. When you retrieve you data it will return an NSSet, which is unsorted so you will have to have some way of sorting the data in the array such as a unique id number assocaited with each object you create.

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