解决 pathForResource 返回 nil的问题

点击(此处)折叠或打开

  1. NSString* path = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"xml"]; 
  2. NSLog(@"path=%@",path); 
  3. NSError *error=nil; 
  4. NSString* fileText = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error]; 
  5. NSLog(@"%@",error); 
  6. NSLog(@"path:%d , fileText:%d",[path retainCount],[fileText retainCount]);

结果在 stringWithContentsOfFile出现错误“The operation couldn’t be completed

追查发现是pathForResource返回nil,我查了半天没有找到解决办法,我尝试找Default.png,发现能够找到在"/Users/admin/Library/Application Support/iPhone Simulator/6.0/Applications/FFB75F5F-86B7-4B74-9CEF-9F76DE56764C/BaseAppKit.app/"目录下,而在这个目录下确没有sample.xml,我忽然想到了可能需要在项目配置文件里告诉编译器把sample.xml拷贝到BaseAppKit.app/下,

果然我找到了添加资源的地方:

单击项目-》Build phases-》若是没有“copy files”就需要添加:

添加文件:

添加完后再运行就找到文件了

原文地址:https://www.cnblogs.com/mafeng/p/5831628.html