我正在做一些关于写入文件和从文件加载的练习。
我创建了一个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:你好世界