将NSMutableArray写入文件并将其加载回 [英] Write an NSMutableArray to a file and load it back

查看:94
本文介绍了将NSMutableArray写入文件并将其加载回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些关于写入和从文件加载的练习。



我创建了一个 NSString ,然后将其写入文件,然后再次加载 NSString 。简单。



如何使用 NSMutableArray NSStrings ,或更好的 NSMutableArray 我自己的类?

  #import< Foundation / Foundation.h> 

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

@autoreleasepool {

// ...

//将NSString写入文件
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];

//从文件加载NSString
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;
}

列印:str2:hello world

 <$ c $ 

c> // save it

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

//加载它

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]

//保存

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

//从文件加载NSString

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

虽然我用数组说明了这个技术,但它适用于符合NSCoding(其中包括许多基本的Cocoa类,如字符串,数组,字典, NSNumber 等)。如果你想让自己的类使用 NSKeyedArchiver ,那么你也必须使它们符合 NSCoding 。有关详细信息,请参见归档和序列化编程指南。 p>

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

解决方案

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.

这篇关于将NSMutableArray写入文件并将其加载回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆