Write an NSMutableArray to a file and load it back

2019-02-24 00:30发布

问题:

I'm doing some exercises about writing to and loading from a file.

I've created an NSString, then written it to a file, and then loaded an NSString again. Simple.

How can I do this with an NSMutableArray of NSStrings, or better an NSMutableArray of my own class?

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        // insert code here...

        //write a NSString to a file
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"file.txt"];

        NSString *str = @"hello world";
        NSArray *myarray = [[NSArray alloc]initWithObjects:@"ola",@"alo",@"hello",@"hola", nil];

        [str writeToFile:filePath atomically:TRUE encoding:NSUTF8StringEncoding error:NULL];

        //load NSString from a file
        NSArray *paths2 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory2 = [paths2 objectAtIndex:0];
        NSString *filePath2 = [documentsDirectory2 stringByAppendingPathComponent:@"file.txt"];
        NSString *str2 = [NSString stringWithContentsOfFile:filePath2 encoding:NSUTF8StringEncoding error:NULL];

        NSLog(@"str2: %@",str2);

    }
    return 0;
}

Printed: str2: hello world

回答1:

If you want to write your array as a plist, you can

// save it

NSArray *myarray = @[@"ola",@"alo",@"hello",@"hola"];
BOOL success = [myarray writeToFile:path atomically:YES];
NSAssert(success, @"writeToFile failed");

// load it

NSArray *array2 = [NSArray arrayWithContentsOfFile:path];
NSAssert(array2, @"arrayWithContentsOfFile failed");

For more information, see Using Objective-C Methods to Read and Write Property-List Data in the Property List Programming Guide.

But, f you want to preserve the mutability/immutability (i.e. the precise object types) of your objects, as well as open up the possibility of saving a wider array of object types, you might want to use an archive rather than a plist:

NSMutableString *str = [NSMutableString stringWithString:@"hello world"];
NSMutableArray *myarray = [[NSMutableArray alloc] initWithObjects:str, @"alo", @"hello", @"hola", nil];

//save it

BOOL success = [NSKeyedArchiver archiveRootObject:myarray toFile:path];
NSAssert(success, @"archiveRootObject failed");

//load NSString from a file

NSMutableArray *array2 = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSAssert(array2, @"unarchiveObjectWithFile failed");

While I illustrate the technique with an array, it works with any object that conforms to NSCoding (which includes many of the basic Cocoa classes like strings, arrays, dictionaries, NSNumber, etc.). If you want to make your own classes work with NSKeyedArchiver, then you must make them conform to NSCoding, too. For more information, see the Archives and Serializations Programming Guide.



回答2:

This document at Apple walks you through the process.