繁体   English   中英

如何在xcode中的NSString中使用变量作为文件名?

[英]How to use variable for file name in NSString in xcode?

这是示例代码。 如何使用此变量:“ Readme.txt”作为文件名? 提前致谢。

NSString *file_name = [NSString stringWithFormat:@"Readme"];
NSString *filePath=[[NSBundle mainBundle] pathForResource:@"%@",file_name  ofType:@"txt"];

您可以简单地传入变量。

NSString *filePath = [[NSBundle mainBundle] pathForResource:file_name ofType:@"txt"];

另外,由于您将file_name定义为常量字符串,因此无需使用stringWithFormat:方法。 您可以直接定义它。

NSString *file_name = @"Readme";

如果file_name变量每次都是Readme,则它是一个常量,根本不需要定义:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Readme" ofType:@"txt"];

你做错了,

NSString *filePath=[[NSBundle mainBundle] pathForResource:@"%@",file_name  ofType:@"txt"];

而不是那样的代码,

NSString *filePath=[[NSBundle mainBundle] pathForResource:file_name ofType:@"txt"];
NSString *file_name = @"Readme.txt";

NSString *name = [file_name stringByDeletingPathExtension];
NSString *extension = [file_name pathExtension];

NSString *file_path = [[NSBundle mainBundle] pathForResource:name ofType:extension];
NSString *filePath=[[NSBundle mainBundle] pathForResource:@"Readme"  ofType:@"txt"];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM