把txt转为plist文件

  • 把txt转为plist文件
- (void)textChangeToPlist {
    //读取txt文件的路径
    NSString *txtPath = [[NSBundle mainBundle] pathForResource:NSLocalizedString(@"country_txt", nil) ofType:nil];
    
    //gbk编码 如果txt文件为utf-8的则使用NSUTF8StringEncoding
   //NSStringEncoding gbk = CFStringConvertEncodingToNSStringEncoding(NSUTF8StringEncoding);
    //定义字符串接收从txt文件读取的内容
    NSString *str = [[NSString alloc] initWithContentsOfFile:txtPath encoding:NSUTF8StringEncoding error:nil];
    //将字符串转为nsdata类型
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    //将nsdata类型转为NSDictionary
    NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    
    //写入的路径
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    
    NSString *plistPath1 = [paths objectAtIndex:0];
    //得到完整的文件名
    NSString *filename=[plistPath1 stringByAppendingPathComponent:@"country.plist"];
    
    //写入
    BOOL result = [array writeToFile:filename atomically:YES];
    if (result) {
        //写入成功
        //读取写入的文件
        NSArray *arr = [[NSArray alloc] initWithContentsOfFile:filename];
        
        for (NSDictionary *dict in arr) {
            //保存数据源
            FSCountryModel *model = [FSCountryModel objectWithKeyValues:dict];
            [_countryArr addObject:model];
        }
    }
}

你可能感兴趣的:(把txt转为plist文件)