iOS 文件读写
2019-07-18 本文已影响0人
NapoleonY
向 cache 文件夹中添加 words.plist 文件,并写入 String 数组
- (void)writeArrayToFile {
NSArray *array = @[@"a", @"b", @"c"];
NSString *cachePatch = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [cachePatch stringByAppendingPathComponent:@"myFile.plist"];
NSLog(@"filePath: %@", filePath);
BOOL res = [array writeToFile:filePath atomically:YES];
NSLog(@"res = %d", res);
}
从 cache 文件夹中读取 words.plist 文件中的内容
- (void)readArrayFromFile {
NSString *cachePatch = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [cachePatch stringByAppendingPathComponent:@"myFile.plist"];
NSLog(@"filePath: %@", filePath);
NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
NSLog(@"array: %@", array);
}
从 Bundle 中读取 words.plist 文件中的内容
- (void)readArrayFromBunndleFile {
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"myFile" ofType:@"plist"];
NSLog(@"filePath: %@", filePath);
NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
NSLog(@"array: %@", array);
}
private func getJokeListFromBundleFile() -> [String] {
guard let filePath = Bundle.main.path(forResource: "list", ofType: "plist") else { return [] }
guard let array = NSArray.init(contentsOfFile: filePath) else { return [] }
guard let strArray = array as? [String] else { return [] }
return strArray
}