大伙都知道iphone开发下要经常返回文件夹的路径,但是苹果提供的api返回不同的文件夹又不一样,我在这里统一定义下接口,
以后无论是返回Documents还是Tmp还是应用程序资源文件夹路径都只要直接调用:
[self dataFilePath:@"data.plist" ofType:kDocuments]
下面是源代码:
#define kDocuments 1 /*返回应用程序沙盒下documents文件夹里的文件路径*/
#define kTmp 2 /*返回应用程序沙盒下Tmp文件夹里的文件路径*/
#define kAPP 3 /*返回应用程序沙盒下app文件夹里的文件路径*/
- (NSString *)dataFilePath:(NSString *)file ofType:(int)kType{
NSString *pathFile = nil;
switch (kType) {
case kDocuments:
{
// NSDocumentDirectory代表查找Documents路径,NSUserDomainMask代表在应用程序沙盒下找
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// ios下Documents文件夹只有一个
NSString *documentsDirectory = [paths objectAtIndex:0];
pathFile = [documentsDirectory stringByAppendingPathComponent:file];
break;
}
case kTmp:
{
NSString *str = NSTemporaryDirectory();
pathFile = [str stringByAppendingPathComponent:file];
break;
}
case kAPP:
{
// 获得文件名
NSString *str =[file stringByDeletingPathExtension];
// 获得文件扩展路径
NSString *str2 = [file pathExtension];
pathFile = [[NSBundle mainBundle] pathForResource:str ofType:str2];
break;
}
default:
break;
}
return pathFile;
}