博客> Xcode NSBundle
Xcode NSBundle
2017-10-22 21:51 评论:0 阅读:585 笑笑就好90
ios NSBundle loadFile
Write a little Demo, welcome to use or contact me!
An NSBundle object helps you access the code and resources in a bundle directory on disk. Apple uses bundles to represent apps, frameworks, plug-ins, and many other specific types of content. Bundles organize their contained resources into well-defined subdirectories, and bundle structures vary depending on the platform and the type of the bundle. By using a bundle object, you do not have to know the structure of a bundle to access its resources. The bundle object provides a single interface for locating items, taking into account the bundle structure, user preferences, available localizations, and other relevant factors.
    NSBundle *myBundle = [NSBundle mainBundle];
 NSString *pinMapping = [myBundle pathForResource:@"carbonmap-J140-J680" ofType:@"csv"];
 NSMutableArray *arr = [self initializeXXMapWithContentsOffFile:pinMapping];
 NSLog(@"---%@",arr);
 if ([arr[0][@"Pin"] isEqualToString:@"9"]) {
  NSLog(@"----yes----");
 }

 //use the path load file
    //NSBundle *bundle = [NSBundle bundleWithPath:@"~/.myApp/Good.bundle"];
 //use the url load file
 //bundle = [NSBundle bundleWithURL:[NSURL URLWithString:@"https://www.baidu.com"]];
-(NSMutableArray *)initializeXXMapWithContentsOffFile:(NSString *)file{
 NSError *error = nil;
 NSString *csvContent = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:&error]; //get file
 if ((!csvContent)) { // if the file is empty, return
  NSLog(@"Cannot read .csv file %@ , error :%@",csvContent,error.description);
  return nil;

 }
 NSArray * lines = [csvContent componentsSeparatedByString:@"\n"];
 //Filter the file
 if ([lines count] < 2) { //The .csv file content description line
  NSLog(@"The fiel is empty. fiel:%@",lines);
  return nil;

 }
 //Filter special characters
 NSMutableArray *filterLines = [NSMutableArray arrayWithArray:lines];
 for (NSInteger i= 0; i < filterLines.count; i++) {
  for (NSInteger i = 0; i< filterLines.count; i++) {
   if ([filterLines[i] containsString:@"\r"]) { //or other
    [filterLines replaceObjectAtIndex:i withObject:[lines[i] stringByReplacingOccurrencesOfString:@"\r" withString:@""]];
    }
   if ([filterLines[i] length] == 0) [filterLines removeObjectAtIndex:i];
   }
 }
 //filter over
 lines = filterLines;
 NSArray *key = [lines.firstObject componentsSeparatedByString:@","]; //get dictionary key
 NSMutableArray *ReturnArray = [[NSMutableArray alloc] init];  //return array

 for (NSInteger i = 1; i < lines.count; i++) {
//  if (!tempStr) return nil;   //if tempArr is empty ,return
  NSArray *tempArr = [lines[i] componentsSeparatedByString:@","];
  NSMutableDictionary *tempDic = [[NSMutableDictionary alloc] init];
  for (NSInteger j = 0; j < tempArr.count; j++) {
   [tempDic setObject:tempArr[j] forKey:key[j]];
  }
  [ReturnArray addObject:tempDic];

 }
 return ReturnArray;
}
收藏
1
sina weixin mail 回到顶部