Write NSMutableArray to the file and load it back

I am doing some exercises about writing and loading from a file.

I created NSString, then wrote it to a file, and then downloaded it again NSString. Plain.

How can I do this using NSMutableArrayfrom NSStringsor better than NSMutableArraymy 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

+4
source share
2 answers

If you want to write an array as 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");

. Objective-C .

/ ( ) , , , 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");

, , NSCoding ( Cocoa , , , , NSNumber ..). , NSKeyedArchiver, NSCoding. . .

+9
0

All Articles