iOS将txt文件写入plist文件

读取txt文件,然后改写为plist文件

 -(void)convertTxtToPlist:(NSString *)fileName
 {
//读取文本文件
 NSString *txtPath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"txt"];
 NSString *txtContent = [NSString stringWithContentsOfFile:txtPath encoding:NSUTF8StringEncoding error:nil];

//进行每行的处理
NSArray *txtArry = [txtContent componentsSeparatedByString:@"\r\n"];
NSMutableArray *plistArry = [NSMutableArray array];
for (NSString *question in txtArry) {
    if (isNSString(question)) {
        NSRange range = [question rangeOfString:@","];
        NSString *area_id = [question substringToIndex:range.location];
        NSString *name = [question substringFromIndex:range.location+1];
        name = [name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:area_id,@"area_id",name,@"name", nil];
        [plistArry addObject:dic];
    }
}
//写到plist文件中
NSArray *stringPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [stringPath objectAtIndex:0];
NSString *path = [docDirectory stringByAppendingPathComponent:@"city.plist"];
NSLog(@"%@",path);
[plistArry writeToFile:path atomically:YES];

}

判断字符串为空

bool isNSString(id string)
{
  if (![string isKindOfClass:[NSString class]])
  {
      return NO;
  }
  NSString *str=(NSString *)string;
  if ([str isKindOfClass:[NSNull class]])
  {
      return NO;
  }
  if (str==nil||[str isEqualToString:@""])
  {
      return NO;
  }
  else
  {
      return YES;
  }
}

你可能感兴趣的:(iOS将txt文件写入plist文件)