【问题标题】:Compiled program can't find files编译的程序找不到文件
【发布时间】:2012-10-31 11:30:54
【问题描述】:
NSFileManager *fm=[NSFileManager defaultManager];   
NSString *pathToFile=[NSString stringWithFormat:@"%@/sells", [fm currentDirectoryPath]];
if ([fm fileExistsAtPath:pathToFile] == NO)
{
    return NO;
}
else
{
    if(content)
    {
        [content release];  
    }
    content=[[NSMutableString alloc] initWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:nil];
}
return YES;

它在 XCode 中正常工作,但 my.app 总是返回 NO(“sells”当然存在于它的目录中)。如何解决?

【问题讨论】:

  • 你知道正在运行的应用程序的当前目录是什么吗?如果这些文件在您的包中,那么您需要获取包路径而不是当前目录。
  • 对,你几乎从不使用 iPhone 上的 currentDirectoryPath。这主要是出于歇斯底里的原因。
  • 即使 NSString *pathToFile=[NSString stringWithString:@"sells"]; (文件与应用程序位于同一目录中)它返回 NO :(

标签: objective-c osx-snow-leopard


【解决方案1】:

这是您通常访问 App bundle 中单个文件的方式:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"yourFile" ofType:@"ext"];  
NSData *fileData = [NSData dataWithContentsOfFile:filePath];  

这就是访问目录的方式:

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *path = [documentsDir stringByAppendingPathComponent:@"fileName"];
    if(![fileManager fileExistsAtPath:path])
    {
        // foo bar
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    相关资源
    最近更新 更多