我正在做一些关于写入和加载文件的练习。
我创建了NSString
,然后将其写入文件,然后再次加载NSString
。简单。
如何使用NSMutableArray
NSStrings
或更好NSMutableArray
我自己的班级来完成此操作?
#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;
}
印刷:str2:你好世界
答案 0 :(得分:10)
如果您想将数组编写为plist,可以
// 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");
有关详细信息,请参阅属性列表编程指南中的Using Objective-C Methods to Read and Write Property-List Data。
但是,如果你想保留对象的可变性/不变性(即精确的对象类型),并且打开保存更多对象类型的可能性,你可能想要使用存档而不是一个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
。有关详细信息,请参阅Archives and Serializations Programming Guide。
答案 1 :(得分:0)