繁体   English   中英

[iPhone Xcode]如何获取模拟器/设备上资源的路径?

[英][iPhone Xcode]How can I get path to resource on simulator/device?

如何获得模拟器和设备上的资源的路径? 我有这个代码:[代码] NSString * tytul = [NSString stringWithUTF8String:tytul_c];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *myPathDocs =  [documentsDirectory stringByAppendingPathComponent:tytul];

const char *sciezka;
if (![[NSFileManager defaultManager] fileExistsAtPath:tytul])
{
    NSString *stringWithoutTXT = [tytul stringByReplacingOccurrencesOfString:@".txt" withString:@""];


    NSString *myPathInfo = [[NSBundle mainBundle] pathForResource:stringWithoutTXT ofType:@"txt"];
    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSLog(@"%@",myPathDocs);

    //sciezka = [myPathDocs UTF8String];
    sciezka = [myPathInfo UTF8String];
    return sciezka;
}

[/码]

而且它可以在设备上正常运行,但不能在模拟器上运行。 我该如何解决? 我应该把资源放在哪里? 现在,我将它们放在“文档”的项目文件夹中。 可以吗

您正在以某种方式混合资源和文档/临时文件。

资源是一个文件,您将其添加到XCode项目中,并在目标“复制包资源”构建阶段中列出。 资源中没有子文件夹,但是您可以添加捆绑作为资源,而捆绑又包含其他资源。 您会得到如下路径的NSString:

[[UIBundle mainBundle] pathForResource:@"filename" ofType:@"extension"];
[UIBundle bundleWithPath:[[UIBundle mainBundle] pathForResource:@"subbundle" ofType:@"bundle"] pathForResource:@"filename" ofType:@"extension"];

文档,临时文件和缓存是应用程序在运行时写入的文件。 这些通常存储在您可以通过NSSearchPathForDirectoriesInDomains访问的目录之一中。

您的代码应为您提供前三行之后的路径:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *myPathDocs =  [documentsDirectory stringByAppendingPathComponent:tytul];

如果要检查此文件是否存在,则应使用myPathDocs而不是tytul ,后者仅包含文件名或相对路径。

if (![[NSFileManager defaultManager] fileExistsAtPath:myPathDocs])
{
    return [myPathDocs UTF8String];
}
return NULL;

暂无
暂无

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

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